Object constructor
suggest changeEvery constructor chain ends in a constructor of the direct superclass, and ultimately in Object. A constructor calls that superclass constructor with super(...), which must be the first statement, so superclass initialization finishes before the rest of this constructor runs.
If you do not write super(...) or this(...), the compiler inserts super().
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 another constructor as the first statement of a constructor. An explicit superclass constructor call and a call to another constructor of the same class both have to be the first statement, so 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")) calls the second constructor with the list. That constructor delegates to the first with the list's size (which then calls super() implicitly) and then calls addInitialValues(initialValues) with 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 call new MyClass(3) or new MyClass(Arrays.asList("a", "b", "c")). 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 it is 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 invokes the <init> method with the invokespecial instruction. That method can be invoked only on uninitialized class instances.
For more information take a look at the JVM specification and the Java Language Specification:
- Special Methods (JVM) - JVMS - 2.9
- Constructors - JLS - 8.8