I have three classes:
public class A {
public A(){
System.out.println("in A");
}
}
public class B extends A{
public B(){
System.out.println("in b");
}
}
public class C extends B{
public C(){
System.out.println("in C");
}
}
Now I am really not sure how the constructor calls work.
If I instantiate C c= new C();
, in what order (and why that order) does the constructors get called.
If I instantiate the class C, then should not it just check if the class C has got any constructor or not and if it does, it shall use it?
Why does it output-> In A In B In C?
Doesn't it go up in the hierarchy only when it doesn't find the constructor in it's own class? Or the constructors of the super class are called implicitly every time?
Super constructor are called by default from the base class constructor.
The only case in which you should call a super class constructor with super, is when you need to explicitly pass a parameter to the super class constructor itself.
So the answer is yes, they are all called. The order is from the most up class in the hierarchy down to the base class, so : A, B, C.
Default constructors are always invoked, and are invoked top-down - from the topmost super-class to the lowest base-class.
Note that the super(...)
call is necessary only for parameterized constructors. In your case you don't have any, so the default gets called automatically.
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