Consider this code:
class Test { Test() { System.out.println("In constructor of Superclass"); } int adds(int n1, int n2) { return(n1+n2); } void print(int sum) { System.out.println("the sums are " + sum); } } class Test1 extends Test { Test1(int n1, int n2) { System.out.println("In constructor of Subclass"); int sum = this.adds(n1,n2); this.print(sum); } public static void main(String[] args) { Test1 a=new Test1(13,12); Test c=new Test1(15,14); } }
If we have a constructor in super class, it will be invoked by every object that we construct for the child class (ex. Object a
for class Test1
calls Test1(int n1, int n2)
and as well as its parent Test()
).
Why does this happen?
The output of this program is:
In constructor of Superclass
In constructor of Subclass
the sums are 25
In constructor of Superclass
In constructor of Subclass
the sums are 29
Why creating an object of the sub class invokes also the constructor of the super class? When inheriting from another class, super() has to be called first in the constructor. If not, the compiler will insert that call. This is why super constructor is also invoked when a Sub object is created.
To explicitly call the superclass constructor from the subclass constructor, we use super() . It's a special form of the super keyword. super() can be used only inside the subclass constructor and must be the first statement.
The constructors of the subclass can initialize only the instance variables of the subclass. Thus, when a subclass object is instantiated the subclass object must also automatically execute one of the constructors of the superclass. To call a superclass constructor the super keyword is used.
Explicit Constructor Chaining using this() or super() To call a non-default superclass constructor from a subclass, use the super() keyword. For instance, if the superclass has multiple constructors, a subclass may always want to call a specific constructor, rather than the default.
Because it will ensure that when a constructor is invoked, it can rely on all the fields in its superclass being initialised.
see 3.4.4 in here
Yes. A superclass must be constructed before a derived class could be constructed too, otherwise some fields that should be available in the derived class could be not initialized.
A little note: If you have to explicitly call the super class constructor and pass it some parameters:
baseClassConstructor(){ super(someParams); }
then the super constructor must be the first method call into derived constructor. For example this won't compile:
baseClassConstructor(){ foo(); super(someParams); // compilation error }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With