Can anyone explain how this constructor call is working. Because I was assuming that it should print
hello from class A
hello from class B
hello from class C
I am confused here. Any help is appreciated. Below is my code.
public class A {
A(){
System.out.println("hello from class A");
}
}
public class B extends A {
B(){
System.out.println("hello from class B");
}
}
public class C extends B {
C(B b){
System.out.println("hello from class C");
}
public static void main(String[] args) {
new C(new B());
}
}
//result
hello from class A
hello from class B
hello from class A
hello from class B
hello from class C
Each constructor of a derived class first constructs its base class: So first you create an object of class B, resulting in A() to be called first. Then you create an object of class C, resulting in A() and B() to be called first.
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