Java Language Object constructor


Example

All constructors in Java must make a call to the Object constructor. This is done with the call super(). This has to be the first line in a constructor. The reason for this is so that the object can actually be created on the heap before any additional initialization is performed.

If you do not specify the call to super() in a constructor the compiler will put it in for you.

So all three of these examples are functionally identical

with explicit call to super() constructor

public class MyClass {

    public MyClass() {
        super();
    }
}

with implicit call to super() constructor

public class MyClass {

    public MyClass() {
        // empty
    }
}

with implicit constructor

public class MyClass {

}

What about Constructor-Chaining?

It is possible to call other constructors as the first instruction of a constructor. As both the explicit call to a super constructor and the call to another constructor have to be both first instructions, they are mutually exclusive.

public class MyClass {

    public MyClass(int size) {

        doSomethingWith(size);

    }

    public MyClass(Collection<?> initialValues) {

        this(initialValues.size());
        addInitialValues(initialValues);
    }
}

Calling new MyClass(Arrays.asList("a", "b", "c")) will call the second constructor with the List-argument, which will in turn delegate to the first constructor (which will delegate implicitly to super()) and then call addInitialValues(int size) with the second size of the list. This is used to reduce code duplication where multiple constructors need to do the same work.

How do I call a specific constructor?

Given the example above, one can either call new MyClass("argument") or new MyClass("argument", 0). In other words, much like method overloading, you just call the constructor with the parameters that are necessary for your chosen constructor.

What will happen in the Object class constructor?

Nothing more than would happen in a sub-class that has a default empty constructor (minus the call to super()).

The default empty constructor can be explicitly defined but if not the compiler will put it in for you as long as no other constructors are already defined.

How is an Object then created from the constructor in Object?

The actual creation of objects is down to the JVM. Every constructor in Java appears as a special method named <init> which is responsible for instance initializing. This <init> method is supplied by the compiler and because <init> is not a valid identifier in Java, it cannot be used directly in the language.

How does the JVM invoke this <init> method?

The JVM will invoke the <init> method using the invokespecial instruction and can only be invoked on uninitialized class instances.

For more information take a look at the JVM specification and the Java Language Specification: