This is a very basic question on Java. I’ve read somewhere that at first in the subclass’s constructor the constructor of the super class is implicitly called. But I couldn’t find the reference to the documentation, to read about that in detail. Could someone please provide this reference?
Here is an example of what I’m talking about, that outputs the super sub string:
class SuperClass {
static String s = "";
protected SuperClass() { s += "super "; }
}
public class SubClass extends SuperClass {
private SubClass() { s += "sub"; }
public static void main(String[] args) {
new SubClass();
System.out.println(s);
}
}
There’s no overriding of constructors in Java – they’re not called polymorphically to start with.
But each constructor has to call a constructor of the superclass, either implicitly (calling a parameterless one) or explicitly (with
super(...)as the first line of the constructor body – or chain to another constructor within the same class, withthis(...)as the first line of the constructor body. The chained constructor is executed before the rest of the constructor body.See section 8.8.7 of the Java Language Specification for more details.