[Solved] What is the output ? How?


Let’s try to visualize what happens by adding some more prints:

class B{
    B(){
        System.out.println("binit");
        f();
    }
    public void f(){
        System.out.println("B ctor");
    }
}

class A extends B{
    A(){
        System.out.println("ainit");
        f();
    }

    @Override
    public void f(){
        System.out.println("A ctor");
    }

    public static void main(String[] args) {
        System.out.println(1);
        A a = new A();
        System.out.println(2);
        a.f();
        System.out.println(3);
        B b = new B();
        System.out.println(4);
        b.f();
    }
}

Our output is now:

1
binit
A ctor
ainit
A ctor
2
A ctor
3
binit
B ctor
4
B ctor

So what’s happening here? Between 1 and 2 we have two initialization, even though we have instantiated only A. This is because subclasses (A extends B) will, by default, call the superclass (B in this case) constructor as first thing on instantiation. And the constructor of B calls f(). But this f has been overriden by A, instead than printing “B ctor” will print “A ctor”.
After that, the constructor of A runs, and prints “A ctor” by calling his own overrode f.

What happens after 2 is pretty straightforward. The only difference is that when we instantiate B (after 4), we are not using the overrode f, but the original one, so we print “B ctor”.

Got it?

1

solved What is the output ? How?