Search code examples
javainheritanceconstructorsuperclass

What does the default constructor in the class OBJECT do?


I'm a Java beginner learning about Java compiler rules as below:

  1. If the class has no super class, extend it to Object class
  2. If the class has no constructor, add a default no-parameter constructor
  3. If the first line of the constructor is not "super()" or "this()", add "super()" to call the default constructor of the super class.

I understand that all objects we create are derived from the super class Object. My question is what does the constructor in the Object class do when called?

Edit: My question is about what the constructor does in the class Object? I'm aware that subclasses call superclass's constructor by default.

For example, I have the following code (where I explicitly extend to Object and call super() to illustrate what the compiler does). My question is, what does the call to super() do?

public class Person extends Object
{
    private String name;
    public Person(String n)
        {   
            super();
            this.name = n;
        }
}

Solution

  • My question is, what does the call to super() do?

    It calls the default constructor for java.lang.Object. And to answer what you seem to be really asking, from the Java Language Specification, #8.8.9

    8.8.9. Default Constructor

    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.

    Note the final paragraph.