javaconstructor

Code calls new GenericObject() but GenericObject.java doesn't have a constructor


I'm looking through some code that I'm working with and one bit of it strikes me in particular:

In the file there is a block:

public void prepare(){
    if (this.GenericObjectID != null) 
         doStuff();
    else{
         this.GenericObjet = new GenericObject();
    }

However, when I look through GenericObject.java there is no constructor at all. The code runs, but I didn't write it, so I'm not positive how (yet!). So my question is: how is this possible? What is the java compiler doing when it sees this call but then no constructor in the file that describes the object?


Solution

  • If there are no explicit constructors, then the compiler creates an implicit default constructor, with no arguments, that does nothing but implicitly call the superclass constructor.

    Section 8.8.9 of the JLS talks about default constructors:

    If a class contains no constructor declarations, then a default constructor is implicitly declared. The form of the default constructor for a top level class, member class, or local class is as follows:

    • The default constructor has the same accessibility as the class (§6.6).

    • The default constructor has no formal parameters, except in a non-private inner member class, where the default constructor implicitly declares one formal parameter representing the immediately enclosing instance of the class (§8.8.1, §15.9.2, §15.9.3).

    • The default constructor has no throws clauses.

    • If the class being declared is the primordial class Object, then the default constructor has an empty body. Otherwise, the default constructor simply invokes the superclass constructor with no arguments.