javaconstructordefault-constructor

Java default constructor


What exactly is a default constructor — can you tell me which one of the following is a default constructor and what differentiates it from any other constructor?

public Module() {
   this.name = "";
   this.credits = 0;
   this.hours = 0;
}

public Module(String name, int credits, int hours) {
   this.name = name;
   this.credits = credits;
   this.hours = hours;
}

Solution

  • Neither of them. If you define it, it's not the default.

    The default constructor is the no-argument constructor automatically generated unless you define another constructor. Any uninitialised fields will be set to their default values. For your example, it would look like this assuming that the types are String, int and int, and that the class itself is public:

    public Module()
    {
      super();
      this.name = null;
      this.credits = 0;
      this.hours = 0;
    }
    

    This is exactly the same as

    public Module()
    {}
    

    And exactly the same as having no constructors at all. However, if you define at least one constructor, the default constructor is not generated.

    See the Java specifications, specifically: Section 8.8.9. Default Constructor of Java Language Specification.

    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 access modifier as the class, unless the class lacks an access modifier, in which case the default constructor has package access (§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 clause.

    Clarification

    Technically it is not the constructor (default or otherwise) that default-initialises the fields. However, I am leaving it the answer because