Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constructor call

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?

like image 228
Kraken Avatar asked Sep 20 '11 14:09

Kraken


2 Answers

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.

like image 74
Heisenbug Avatar answered Sep 30 '22 08:09

Heisenbug


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.

like image 29
Saket Avatar answered Sep 30 '22 10:09

Saket