Object Constructors

Well, I heard this from my "Object Oriented Programming, Distributed Computing, and Web Services" teacher:
A constructor cannot call any method on it's code. Of course you can code-it to call te method, but it would be bad OO programming. Is that true? If so... ALL JAVA OBJECT CONSTRCUTORS WORK THAT WAY
( java.util.LinkedList.LinkedList(java.util.Collection clct),
java.util.StrinkTokenizer.StringTokenizer(java.util.String str),
java.lang.Integer(int value), as some examples...) ???
THNX

mm.. I but I'm not talking about invoking methods like
utilities or something, but 2initializer methods".. I
dunno, but I wrote the LinkedList(Collections cl)
example.. how does the constructor works... would it
be possible it calls a method who parses the
collection to a LinkedList, or in any other example, I
hava a Traingle Class with a constructor which
receives 3 int arguments one for each side, for
example you give negative parameters, or arguments
which cannot create a real Triangle (they dissmatch
when drawing it, for example) could you call a
validation method?? or just create it?? Yes it's perfectly fine to create a method to be called by the constructor. Often it's the only good design choice.
As mentioned above, you should avoid calling non-final, non-private, non-static methods from the constructor of a class. You can't be sure what the method will do or whether it will execute successfully. There is more to this issue than just that but if you find that you need to call an abstract or non-final method from a constructor, you consider refactoring the class using a Factory method or the AbstractFactory pattern.
But there should be no major problems calling private or final or static methods.

Similar Messages

  • Using SequenceFactory getNext in persistent object constructor

    Hi,
    Rightly or wrongly (maybe wrongly cos I am getting problems...)
    In my persistent object constructors, I am initialising the objects id
    field using the sequence factory getNext() method.
    If I run the schematool on a blank DB with no tables then it works fine -
    classes are enhanced, tables created.
    But if I run it again on the same db, it fails on the first persistent
    object, with this stack trace:
    [java] java.lang.ExceptionInInitializerError:
    javax.jdo.JDOFatalUserException: The system could not initialize; the
    following registered persistent types are missing metadata or have not
    been enhanced: [class com.rabobank.reef.tradeadapters.dto.ReefSystem].
    [java] at
    com.solarmetric.kodo.impl.jdbc.JDBCPersistenceManagerFactory.loadPersistentTypes(JDBCPersistenceManagerFactory.java:293)
    [java] at
    com.solarmetric.kodo.impl.jdbc.JDBCPersistenceManagerFactory.setup(JDBCPersistenceManagerFactory.java:256)
    [java] at
    com.solarmetric.kodo.runtime.PersistenceManagerFactoryImpl.privateSetup(PersistenceManagerFactoryImpl.java:872)
    [java] at
    com.solarmetric.kodo.runtime.PersistenceManagerFactoryImpl.getConnectionFactory(PersistenceManagerFactoryImpl.java:223)
    [java] at
    com.solarmetric.kodo.impl.jdbc.JDBCPersistenceManagerFactory.setLogWriter(JDBCPersistenceManagerFactory.java:175)
    [java] at com.rabobank.util.kodo.JDOFactory.<init>(Unknown Source)
    [java] at com.rabobank.util.kodo.JDOFactory.getInstance(Unknown
    Source)
    [java] at
    com.rabobank.util.kodo.JDOFactory.getNextPrimaryKey(Unknown Source)
    [java] at
    com.rabobank.reef.tradeadapters.dto.GenericObject.<init>(Unknown Source)
    [java] at
    com.rabobank.reef.tradeadapters.dto.ReefSystem.<init>(Unknown Source)
    [java] at
    com.rabobank.reef.tradeadapters.dto.ReefSystem.<clinit>(Unknown Source)
    [java] at java.lang.Class.forName0(Native Method)
    [java] at java.lang.Class.forName(Class.java:115)
    [java] at
    com.solarmetric.kodo.impl.jdbc.schema.SchemaTool.main(SchemaTool.java:1115)
    [java] Exception in thread "main"
    Which looks like the sequence factory requires an initialised system to be
    accessed, but it is trying to init the system when it is called?
    But it works on a clean db...
    I am just going about this the wrong way or is it a simple bug in my
    procedure?
    Thanks,
    Chris

    heres the exact error message im getting
    Exception in thread "main" java.lang.NullPointerException
    at instrument.<init>(instrument.java:15)
    at iContainer.populate(iContainer.java:34)
    at main.main(main.java:7)
    the bolded line is the erroneous one
    public instrument(int newID, String newType, String newRenters [], int newPrice, String newKey, boolean newNeedsRepairs)
              super(newID);
              type = newType;
              for ( int x = 0; x < newRenters.length; x++)
                   *renters[x] = newRenters[x];*
              price = newPrice;
              key = newKey;
              needsRepairs = newNeedsRepairs;
         }

  • Database access code in objects constructor, or in data access object

    Given an object that is stored in a database, is it better to have the database access code in a constructor method, or a data access layer object? E.g. I have a Person class
    public class Person{
    int Id;
    String name;
    int age;
    }When I want to read a person's details from the database, I could use a constructor something like this:
    public Person(int id){
    Connection con = getDatabaseConnection();
    ResultSet rs = con.createStatement().executeQuery("Select name, age from person where person_id = " + id);
    rs.next();
    this.name = rs.getString(1);
    this.age=rs.getInt(2);
    }Or I could use a method in a data access object :
    public Person getPerson(int id){
    Person p = new Person();
    Connection con = getDatabaseConnection();
    ResultSet rs = con.createStatement().executeQuery("Select name, age from person where person_id = " + id);
    rs.next();
    p.setName(rs.getString(1));
    p.setAge(rs.getInt(2));
    return p;
    }It seems to me that the constructor approach has two advantages
    (1) the SQL code is kept in the relevant class (so if I want to add a field to Person, I only have to make changes to the Person class)
    (2) I don't have to have a setter method for each field
    Is one or other of these ways generally recognized as 'best practise'?

    malcolmmc wrote:
    But then, on the other hand, everytime a Person gains a new field that's two places you have to change it. if the persistence interface is written in terms of the object and uses ORM, I don't have to touch the implementation. all i have to do is update the object, the database, and the mapping - just like you and your home brew ORM.
    besides, so what? i'd fear the resource leak, bad layering, more difficult testing more.
    Actually lately I've used annotations to label setters with database field names and run a simple home brew ORM to convert rows into objects even when not using a more complex persistence manager.home brew ORM? why is that necessary when you can choose from hibernate, ibatis, jdo, jpa, etc.? that's just nuts.
    %

  • Static nonstatic class object constructor

    I was wonderring what is the use of non static constructors??
    we all know about static constructors, they are used for initializing the class.
    we all know about constructos, they are used for initializing an object from a given class.
    what I dont know is the use of non static constructors such as this
    class A{
         static{
              System.out.println ("Class A Static Constructor");
              /*What is the use of this???????
               *why dont we put this inside the constructor??
              System.out.println ("Class A NON static constructor");
         A(){
              System.out.println ("Class A Constructor");
    class B extends A{
         static{
              System.out.println ("Class B static constructor");
              System.out.println ("Class B NON static Constructor");
         B(){
              System.out.println ("Class B Constructor");
    public class Test{
         public static void main(String[]args){
              new B();
              new B();
    }I would appreciate understaind this!! I can only see that if there was no other constructor, it can be used instead of the default constructor() with no arguments,
    any clarification?

    They are called static and non static intializer.
    The non static initializer was introduced in the language subsequently with inner classes.
    It's used the give an anonymous inner class a feature that behaves like a constructor (though with no args).
    It's useless for other kinds of class.
    abstract class A{
         A(){
              System.out.println("A constructor");
         abstract void exec();
    class B{
         static A getA(){
              return new A(){
                             System.out.println("the cool implementation");
                        void exec(){
                             System.out.println("exec()");
         public static void main( String[] args){
              A a = B.getA();
              a.exec();
    }Cut and paste in a new text file, call it B.java, then javac B.java, and java B.

  • JSP tags as object constructors?

    Hi,
    I want to instantiate an object in a tag handler and then use the object in my JSP code. For example:
    <objConstructor varName="myObj" field1="foo" field2="bar" />
    <%
    out.println(myObj.getField1() + " " + myObj.getField2());
    %>
    Is there an elegant way to do this in JSP, or is there a more appropriate way? I want to allow non-programmers to edit the stuff.
    Thanks,
    Greg

    Sure, you just need to add a TEI class for your tag. So if your tag class is named ObjConstructor.java, you'd need a class called ObjConstructorTEI.java that looks something like this:
    import javax.servlet.jsp.tagext.*;
    public class ObjConstructorTEI extends TagExtraInfo
       public VariableInfo[] getVariableInfo(TagData data)
          VariableInfo info1 = new VariableInfo(data.getAttributeString("id"),"class.name.for.the.object", true, VariableInfo.AT_BEGIN);
          VariableInfo[] info = { info1 } ;
          return info;
    }Note: I changed your varName to id in this example, just to follow the convention used by other tags like jsp:useBean.
    I copied it from a tag I wrote a while back, so I don't remember the specifics of the VariableInfo API, but since you're using it the same way as I did, it should work.

  • How to get a method to call the correct passed object in the constructor

    I have 2 constructors for a certain object:
    public class ABC{
    //variables
    private DEF def;
    private GHI ghi;
    public ABC(DEF def){
    this.def = def;
    someMethod();
    public ABC(GHI ghi){
    this.ghi = ghi;
    someMethod();
    }Now, this someMethod() references / calls a method from the 2 classes passed in the constructor say def.getSome() and ghi.getSome().
    Depending on which constructor is used, it should call the respective xxx.getSome(). Do I need to write 2 someMethod()s or is there a way that one method will call the proper xxx.getSome() ?
    Thanks.....

    Hi
    Following the example may be help to you call correct method,
    // Interface QuizMaster
    public interface QuizMaster {
         public String popQuestion();
    // Class StrutsQuizMaster
    public class StrutsQuizMaster implements QuizMaster{
         public String popQuestion() {
              return "Are you new to Struts?";
    // Class SpringQuizMaster
    public class SpringQuizMaster implements QuizMaster{
         public String popQuestion() {
              return "Are you new to Spring?";
    // Class QuizMasterService
    public class QuizMasterService {
         QuizMaster quizMaster;
         public QuizMasterService(SpringQuizMaster quizMaster){
              this.quizMaster = quizMaster;
         public QuizMasterService(StrutsQuizMaster quizMaster){
              this.quizMaster = quizMaster;
         public void askQuestion()
              System.out.println(quizMaster.popQuestion());
    // QuizProgram
    public class QuizProgram {
         public static void main(String[] args) {
              // Option : 1
    // StrutsQuizMaster quizMaster = new StrutsQuizMaster();
    // Option : 2
    SpringQuizMaster quizMaster = new SpringQuizMaster();
              QuizMasterService quizMasterService = new QuizMasterService(quizMaster);                    
              quizMasterService.askQuestion();
    here you can create object of StrutsQuizMaster or SpringQuizMaster and pass into the QuizMasterService object constructor, base on the object correct method will be called.

  • How to create value objects from xml

    I am receiving xml back from my web service ( e4x ). I am
    trying to figure out how to create a value object without having to
    manually fetch each value in the value objects constructor. I am
    using introspecton in my Java web service to do this. Is there such
    a thing in Action Script?
    Anyone done this before that can share some code???? Any help
    would be very much appreciated.

    That's twice now I've heard that. lol.
    I am using Cairngorm and I suppose out of ignorance perhaps,
    I am using VO's. So my web service would return an Object Proxy and
    I have some code that could create objects dynamically from the
    results. The objects had to be simple of course and now they are
    becoming more complex thus the need to change to e4x instead of
    objects.
    So now I am trying to convert the xml result into the desired
    VO to be used throughout the rest of the application. I'm not sure
    how to use Cairngorm without the VO's they are tied to everything.
    Are you familiar with the architecture? Your thoughts?

  • Global create activity with screenflow and constructor

    Hi
    Question 1) Is it possible to get data from database (Oracle) in constructor
    Execute Screen flow in a row (One fer other) if yes how and if
    not how can we do that?
    Question 2) Explain how data can be displayed in JSP with BPM Object
    Please give simple example.
    Thanks in advance

    Sorry, I'm not following what you're asking. Screenflows do not have constructors. Is it possible that you mean an instance variable BPM Object's constructor? If this is the case, I'd suggest you instead keep the BPM Object's constructor very lean.
    You can run SQL from any Automatic task inside a Screenflow, any Automatic activity inside a process or BPM Object's methods that have their "Server Side Method" property set to "Yes". BPM Object constructors have their "Server Side Method" property set to "No" and cannot be changed. While you could invoke another method from the constructor that is server side, I would not recommend doing it. Almost always you'll want fresh data from the database displayed just prior to a presentation being displayed. If you populate information from a database inside your BPM Object's constructor, the information would be populated when the instance gets created in the Begin activity. If an instance takes 3 weeks to reach the 5th activity in the process, this same stale information populated 3 weeks ago when the object was initialized will be displayed in presentations shown in this activity. Presentations can have an initialization method (method run just before the presentation is shown). Consider using presentation initialization methods to retrieve the latest information from the database.
    Hope this helps,
    Dan

  • My constructor method is bogged!

    Hi There,
    I've got some problems with constructor methods in my program, of course the constructors look fine to me, but then faulty code usually looks good to any programmer after enough hours! Here is some of my code, firstly the following snippet shows the objects being instantiated.
    public static ButtonData BtData1;
    public static ButtonData BtData2;
    public static ButtonData BtData3;
    public static ButtonData BtData4;
    public static ButtonData BtData5;
    public static void main(String[] args)
        try{
          inStream = new FileInputStream("ObjStore");
          objStreamIn = new ObjectInputStream(inStream);
          if(objStreamIn.available() == 0)      
            objStreamIn.close();                
            inStream.close();                   
            BtData1 = new ButtonData("Link1",null);
            BtData2 = new ButtonData("Link2",null);
            BtData3 = new ButtonData("Link3",null);
            BtData4 = new ButtonData("Link4","Zero");
            BtData5 = new ButtonData("Link5","Zero");
          else
        }catch(IOException e){}
        GUI xyz = new GUI();            
    }Alot of the above code is related to serialization -- mainly checking to see whether or not objects already exist on file, and if they do not, instantiating them. Notice that the above constructors have different parameters or arguments (I can't remember which word describes it best!) -- it doesn't seem to matter whether I use two strings such as ("Link4","Zero") or ("Link1",null) -- both create errors. The class that is instantiated looks like this:
    import java.io.*;
    public class ButtonData implements Serializable
      String Name;             
      String Path;             
      ButtonData(String Name,String Path)
        this.Name = Name;
        this.Path = Path;
      protected String getName()
        return Name;
      protected String getPath()
        return Path;
      protected void setName()
        Name = Begin.LinkName.getText();
      protected void setPath()
        Path = Begin.ExecT.getText();
    }As far as I can tell the constructor above follows all the relevant syntax rules, as does the first snippet of code that I provided -- where the objects are instantiated. I will probably feel like a real meat head if I have done something dump and obvious, however I have double checked the code and it looks fine to me. When trying to compile the code I get the following error messages (using JBuilder7) -- these error messages highlight the relevant sections of the first code snippet I provided:
    "Begin.java": Error #: 300 : constructor ButtonData(java.lang.String, null) not found in class quicklauncher2.ButtonData at line 61, column 23
    "Begin.java": Error #: 300 : constructor ButtonData(java.lang.String, null) not found in class quicklauncher2.ButtonData at line 62, column 23
    "Begin.java": Error #: 300 : constructor ButtonData(java.lang.String, null) not found in class quicklauncher2.ButtonData at line 63, column 23
    "Begin.java": Error #: 300 : constructor ButtonData(java.lang.String, java.lang.String) not found in class quicklauncher2.ButtonData at line 64, column 23
    "Begin.java": Error #: 300 : constructor ButtonData(java.lang.String, java.lang.String) not found in class quicklauncher2.ButtonData at line 65, column 23If anybody can shed some light on what is going on here it will be greatly appreciated.
    Thanks

    Thanks everybody for your kind constributions, unfortunately I have tried all suggestion provided and have come up with naught. As both classes are in the same package, the question of scope is resolved, and making the ButtonData objects constructor public has no effect on the error messages displayed. I have also modified the ButtonData class so that accessor and mutator methods are public and variables are private, unfortunately this also has had no effect on the immediate error messages. If anybody has further suggestions they will be greatly appreciated. I thought perhaps that the issue with the constructor may be related to the implementation of the serializalbe interface ----->
    beyond that idea I am seriously stuck!

  • Unexpected behavior when creating Objects in a Vector

    I have a situation where Objects in a Vector appear to be getting corrupted. The context is this: I obtain a ResultSet from a database, create a Vector of Strings for each row, and a Vector of these row vectors for the entire ResultSet. This is passed to a method where a POJO is created for each row. This method returns a Vector of these POJOs. In the Object constructor, a String array of initial values is created and also values are assigned to individual variables. Here is a snippet with the Object constructor
    public class RefAuthorItem {
         private final String refKey;
         private String authorKey, firstName, lastName, itemKey;
         private int authorPosition;
         private boolean isDeleted, isNew;
         // Keep a copy of the original values
         private final String[] oldValues;
          * The constructor for the data object item.
          * @param dataVals     a String array of the data values
          * @param isNewVal     boolean true if this is a new item, false if it is
          *                                              an existing item
         public RefAuthorItem(final String[] dataVals, final boolean isNewVal) {
              oldValues = dataVals;
              authorKey = dataVals[RefQueryBuilder.AUTH_NUM];
              firstName = dataVals[RefQueryBuilder.AUTH_FIRST_NAME];
              itemKey = dataVals[RefQueryBuilder.AUTH_PKEY];
              lastName = dataVals[RefQueryBuilder.AUTH_LAST_NAME];
              refKey = dataVals[RefQueryBuilder.AUTH_REF_FKEY];
              isNew = isNewVal;
              isDeleted = false;
              // the author position integer value is used to sort the display
              authorPosition =
                        Integer.parseInt(dataVals[RefQueryBuilder.AUTH_POS]);
         }It seems the oldValues[] values should be identical to the corresponding individual variable values. When the following code is used to create the objects, they are not.
              final boolean isNew = isNewVal;
              Vector<RefAuthorItem> returnSet = new Vector<RefAuthorItem>();
              final String queryString = QueryBuilder
                   .getRefQuery(keyString, tableName);
              Vector<Vector> dataSet = QueryDB.getResultSet(queryString);
              int columnTot = dataSet.firstElement().size();
                    String[] itemVals = new String[columnTot];
              for (Iterator iter = dataSet.iterator(); iter.hasNext();) {
                   Vector element = (Vector) iter.next();
                   for (int i = 0; i < columnTot; i++) {
                        itemVals[i] = (String) element.get(i);
                   RefAuthorItem item = new RefAuthorItem(itemVals, isNew);
                   returnSet.add(item);
              }What happens is this. I returned four rows from the database and the oldValues[] array for each of the four corresponding objects contains the data from the fourth row. However, when I retrieve the corresponding individual values (e.g., authorLastName) from the Object, it is correct. I checked the object values (oldValues versus individual values retrieved via getters) right after the object is created (the line: RefAuthorItem item = new RefAuthorItem(itemVals, isNew);) and get the correct results. Also, results are correct when the itemVals constructor is moved within the loop, as below
              int columnTot = dataSet.firstElement().size();
              for (Iterator iter = dataSet.iterator(); iter.hasNext();) {
                   Vector element = (Vector) iter.next();
                   String[] itemVals = new String[columnTot];
                   for (int i = 0; i < columnTot; i++) {
                        itemVals[i] = (String) element.get(i);
                   RefAuthorItem item = new RefAuthorItem(itemVals, isNew);
                   returnSet.add(item);
              } There is a problem here. Am I missing a subtle Java issue with instantiating the String array within the loop? Or is there a problem with Vectors? Thanks!

    Dear ejp,
    In the non-working code, I rewrite the itemVals[], create a new RefAuthorItem using the itemVals[] and repeat. I checked the RefAuthorItem immediately after it was created (with println()) and the oldValues and individual String values in the object are concordant. However, after the loop is completed (all RefAuthorItems are created and added to the Vector), the oldValues[] in the objects all have the values from the last row. The individual String variables in the object all have the correct value from the ResultSet row.

  • Array of objects as a part of request

    Hi,
    I have a complex type which is a parameter of my web service's method. Is it guarantied
    that the order of object will be the same on client and server side after WLS
    does the deseriliazation?
    For Example (Array of address objects)
    Constructor of Address object takes one value – street name
    If Client side:
    Address[] list = {new Address(“A street”),  new Address(“B street”), new Address(“C
    street”)};
    Can I assume that
    Server side:
    addressList[0] == “A street” ;
    addressList[1] == “B street” ;
    addressList[2] == “C street” ;
    Thanks

    Hi Lukas,
    If you are experiencing an out of order issue with an array after it has
    been "transported", then it most likely is a bug. If you have a
    reproducer, please provide it to our award winning support group.
    Thanks,
    Bruce
    Lukas wrote:
    >
    Hi Bruce,
    thanks for the answer. You answered my question. I was wondering about the order
    if there is a chance that order of submited items (array) will be different after
    WLS server deseriliazation.
    Thanks again,
    Lukas
    Bruce Stephens <[email protected]> wrote:
    Hi Lukas,
    Array of any supported data type is an equivalent XML schema data type
    to a SOAP array [1].
    RU concerned about partial or sparse arrays?
    Thanks,
    Bruce
    [1]
    http://edocs.bea.com/wls/docs81/webserv/assemble.html#1060805
    Lukas wrote:
    Hi,
    I have a complex type which is a parameter of my web service's method.Is it guarantied
    that the order of object will be the same on client and server sideafter WLS
    does the deseriliazation?
    For Example (Array of address objects)
    Constructor of Address object takes one value – street name
    If Client side:
    Address[] list = {new Address(“A street”),  new Address(“B street”),
    new Address(“C> >> street”);
    Can I assume that
    Server side:
    addressList[0] == “A street” ;
    addressList[1] == “B street” ;
    addressList[2] == “C street” ;
    Thanks

  • Errors with CF 8.0.1 hotfix 3 and hotfix 4, "Object Instantiation Exception.Class not found"

    We need to get our servers up to date with the latest ColdFusion hotfixes in order to pass our security scans and policies. We have been following the Adobe instructions for installing the hotfixes, but we’re getting the same errors each time. The CF 8 hotfix 2 works fine, but once we install hotfix 3 and/or hotfix 4, we get the following errors:
    "Object Instantiation Exception.Class not found: coldfusion.security.ESAPIUtils The specific sequence of files included or processed is: C:\ColdFusion\wwwroot\WEB-INF\exception\java\lang\Exception.cfm, line: 12 "
    coldfusion.runtime.java.JavaObjectClassNotFoundException:
    We have dozens of servers running Windows XP, Netscape Enterprise Server 6.1 (I  know, don’t laugh), ColdFusion 8,0,1,195765, and Java Version 1.6.0_04. Just about  the only good thing about running XP on our servers is that it matches  our development boxes, so we have almost mirrored environments for dev,  test, and production. We do NOT have the CF install with the J2EE configuration.
    The crazy thing is, on tech note 51180 (http://kb2.adobe.com/cps/511/cpsid_51180.html), it says that the fix for bug # 71787 (Fix for "Object Instantiation Exception" thrown when calling a Java object constructor or method with a null argument under JDK 1.6.) was added in cumulative hotfix 2. However we don’t see this problem until we go to hotfix 3 (or 4).
    I’ve also been reading that other people had this same problem, and that the CF 8 hotfix 3 was not compatible with certain versions of JDK, then when you read the Adobe site for CF 8.0.1 hotfix 3, it says “Added the updated cumulative hotfix to make it compatible with jdk 1.4.x, 1.5.x and 1.6.x.”, so that makes me think that Adobe was supposed to have fixed this CF 8.0.1 hotfix 3 JDK incompatability issue - but unfortunately it's still not working for us. We have followed the instructions for removing the jar files and starting/restarting the CF server as directed, we’ve tried this 5-6 times, and still no luck.
    Recommendations? Seems like this is a ColdFusion bug to me – one that says is fixed on the Adobe site, but is not fixed in our environment. Please advise, thanks.

    For what it's worth, we had an MXUnit user describe a similar, though not identical, problem after installing the latest hotfixes. In his case, he's getting "NoSuchMethodExceptions".

  • Constructor Inheritance Question

    Here's a quote from the Java Tutorials at http://java.sun.com/docs/books/tutorial/java/javaOO/objectcreation.html :
    "All classes have at least one constructor. If a class does not explicitly declare any, the Java compiler automatically provides a no-argument constructor, called the default constructor. This default constructor calls the class parent's no-argument constructor, or the Object constructor if the class has no other parent. If the parent has no constructor (Object does have one), the compiler will reject the program."
    In order to fully understand this concept, I created two classes: a ClassParent and a ClassChild.
    public class ClassParent
        public static void main(String[] args) {
           ClassParent tester = new ClassParent();
    public class ClassChild extends ClassParent
        public static void main(String[] args) {
            ClassChild child = new ClassChild();
    }Both classes compiled successfully, which raised the following question:
    I understand that the ClassParent default constructor calls the Object's no-argument constructor.
    Does the ClassChild also call the Object's constructor once it realizes that the ClassParent does not have a no-argument constructor?
    And a somewhat non-related question:
    Seeing how ClassParent calls Object's no-argument constructor if it does not have one of its own, does it also extend the Object class?
    Edit: After running the following code, I realized that the answer to my last question is yes:
    public class ClassParent
        public static void main(String[] args) {
           ClassParent tester = new ClassParent();
           boolean test = tester instanceof Object;
           System.out.println(test);
    }Edited by: youmefriend722 on May 26, 2008 1:54 PM

    youmefriend722 wrote:
    I think I'm getting a basic grasp now but want to make sure that I'm not misunderstanding anything.
    Constructor inheritance:
    If a no-argument constructor is invoked but one isn't declared in that class, the superclass's no-argument constructor will be invoked. Well, sort of. If you invoke a constructor that doesn't exist, you get an error. Keep in mind that the invocation and the constructor may both be automatically supplied by the compiler, and that the compiler won't automatically create a no-arg constructor for a class if you define any constructors for that class.
    So if you don't define any constructors in a class, then a no-arg one is created automatically (at compile time) and (at runtime) when you instantiate that class, that no-arg constructor will try to invoke the superclass's no-arg constructor.
    But suppose you do define a constructor, one that takes an argument. Then if you try to invoke a no-arg constructor on that class, you'll get an error, and the superclass's no-arg constructor won't be invoked (because the error happens first).
    If the superclass does not have a constructor, then the superclass's superclass's constructor will be invoked.No. That never happens. Every class has a constructor (although it might have permissions which make it inaccessible, which is a whole other issue we'll worry about later).
    If the superclass does have a constructor but doesn't have a no-argument constructor, then there will be a compile-time error.Only if you try to invoke the no-arg constructor, which might happen implicitly. For example, if you write a superclass with a 2-arg constructor, and you write a subclass with a 1-arg constructor, and the 1-arg subclass's constructor invokes the superclass's 2-arg constructor, then there's no problem, even though in this example, the superclass doesn't have a no-arg constructor.
    Constructors in general:
    In every constructor, the superclass's no-argument constructor will be invoked if the none of the superclass's constructors are explicitly invoked.Yeah, I think that's right.

  • Constructor

    Java Tutorial says that -
    "All classes have at least one constructor. If a class does not explicitly declare any, the Java compiler automatically provides a no-argument constructor, called the default constructor. This default constructor calls the class parent's no-argument constructor, or the Object constructor if the class has no other parent. *If the parent has no constructor (Object does have one), the compiler will reject the program*."
    Question:
    If the class doesn't have a no-argument constructor, and its parent class also doesn't have a no-argument constructor. Then can't we create an object of the class?
    As per the above explanation, the compiler should reject the program. But, as the parent class is a subclass of Object class, and since object class has a no-argument constructor, the no-argument constructor of Object class will be called if we create an object of the class. Am i right? Can someone please have a look and respond?

    sp_acc wrote:
    The tutorial says - If the superclass has no constructor, then the compiler will reject the program.That statement is nonsense, since every class has at least one constructor. Always. No matter what you do.
    Since by default, for every class, a no-arg constructor will be added by the compiler.Correct.
    If you don't define any constructors, the compiler will define a no-arg c'tor that does nothing but calls super().
    So when we create an object of Subclass, it calls the Superclass no-arg constructorOnly if we don't explicitly call some other this(...) or super(...) c'tor.
    > (which is not present, but included by the compiler by default),
    Unless we've provided one or more explicit c'tors in the superclass, in which case we get a compiler error because we're trying to call a super() that doesn't exist.

  • Constructor and Class constructor

    Hi all
    Can any one explain me the functionality about Constructor and class constructor??
    As well as normal methods, which you call using CALL METHOD, there are two special methods
    called CONSTRUCTOR and CLASS_CONSTRUCTOR, which are automatically called when you
    create an object (CONSTRUCTOR) or when you first access the components of a class
    (CLASS_CONSTRUCTOR)
    I have read the above mentioned document from SAP Documents but i found it bit difficult to understand can any one please help me on this??
    Thanks and Regards,
    Arun Joseph

    Hi,
    Constructor
    Implicitly, each class has an instance constructor method with the reserved name constructor and a static constructor method with the reserved name class_constructor.
    The instance constructor is executed each time you create an object (instance) with the CREATE OBJECT statement, while the class constructor is executed exactly once before you first access a class.
    The constructors are always present. However, to implement a constructor you must declare it explicitly with the METHODS or CLASS-METHODS statements. An instance constructor can have IMPORTING parameters and exceptions. You must pass all non-optional parameters when creating an object. Static constructors have no parameters.
    Class Constructor
    The static constructor is always called CLASS_CONSTRUCTER, and is called autmatically before the clas is first accessed, that is before any of the following actions are executed:
    Creating an instance using CREATE_OBJECT
    Adressing a static attribute using ->
    Calling a ststic attribute using CALL METHOD
    Registering a static event handler
    Registering an evetm handler method for a static event
    The static constructor cannot be called explicitly.
    For better understanding check the following code:
    REPORT  z_constructor.
          CLASS cl1 DEFINITION
    CLASS cl1 DEFINITION.
      PUBLIC SECTION.
        METHODS:
          add,
          constructor IMPORTING v1 TYPE i
                                v2 TYPE i,
          display.
        CLASS-METHODS:
         class_constructor.
      PRIVATE SECTION.
        DATA:
        w_var1   TYPE i,
        w_var2   TYPE i,
        w_var3   TYPE i,
        w_result TYPE i.
    ENDCLASS.                    "cl1 DEFINITION
          CLASS cl1 IMPLEMENTATION
    CLASS cl1 IMPLEMENTATION.
      METHOD constructor.
        w_var1 = v1.
        w_var2 = v2.
      ENDMETHOD.                    "constructor
      METHOD class_constructor.
        WRITE:
        / 'Tihs is a class or static constructor.'.
      ENDMETHOD.                    "class_constructor
      METHOD add.
        w_result = w_var1 + w_var2.
      ENDMETHOD.                    "add
      METHOD display.
        WRITE:
        /'The result is =  ',w_result.
      ENDMETHOD.                    "display
    endclass.
    " Main program----
    data:
      ref1 type ref to cl1.
    parameters:
      w_var1 type i,
      w_var2 type i.
      start-of-selection.
      create object ref1 exporting v1 = w_var1
                                  v2 = w_var2.
       ref1->add( ).
       ref1->d isplay( ).
    Regards,
    Anirban Bhattacharjee

Maybe you are looking for

  • Stability of OS

    Eversince I upgraded to Maverick, the number of OS lock-ups and crashes have increased significantly. Before Maverick, it was may be once in several months but now, when there is any serious work to be done, when a few apps are opened (esp. Safari),

  • Omit the final SUM row in a report using breaks

    We have a report using breaking whereby it is broken for current day, week to date and month to date. We want to use the column SUM feature so that we have a count of all records for the day, week to date and month to date. This works fine, however w

  • Music Player in N81 8GB

    Hello. I have problem with music player, which I can't close. It runs in background all the time. In background should only be standby. I was reading some posts, but I can't find nothing useful. If someone find some solutions or something, please hel

  • Forwarding to Another Domain

    My local Admin have blocked my website but i have another domain, i would like to know how to forward people to my new domain from my old one, just so they don't need to type the complicated name in! So the web page doesn't even load but it redirects

  • Help, can I declare an object using a variable name

    I need to make a bunch of objects using a for loop, so I was wanting to name the object one of the variables that I read. But I basically want to know if I can do this.      private Software makeObject(String proName, int proStock, double proPrice,St