Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How this constructor call is working?

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
like image 543
Hello World Avatar asked Feb 21 '26 20:02

Hello World


1 Answers

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.

like image 72
Frank Puffer Avatar answered Feb 24 '26 10:02

Frank Puffer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!