0

Can anyone explain the output of below code? Trying to extend class A in Class B and overriding method goo() and method foo() is called from the constructor.

public class A {

    public A() {
        foo();
    }

    private void foo() { // Private function foo()
        System.out.print("A::foo ");
        goo();
    }

    public void goo() {
        System.out.print("A::goo ");
    }
}


public class B extends A {

    public B() {
        foo();
    }

    public void foo() {
        System.out.print("B::foo ");
    }

    public void goo() {
        System.out.print("B::goo ");
    }

}


public class C {

    public static void main(String[] args) {
        A b = new B();
    }

}

Output : A::foo B::goo B::foo

Thanks.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724

1 Answers1

8

First, private methods are not inherited. So the foo() in A is different than the foo() in B.

Second, when you call

A b = new B();

The super constructor of B, so A's, is called implicitly so this gets executed first

public A() {
    foo(); // A's version
}

private void foo() { // Private function foo()
    System.out.print("A::foo ");
    goo();
}

goo() is executed polymorphically, ie. B's implementation.

public void goo() {
    System.out.print("B::goo ");
}

Then the B constructor is executed, executing

public B() {
    foo(); // B's version
}

public void foo() {
    System.out.print("B::foo ");
}

Be careful when (directly or indirectly) calling methods that might be overriden from super/parent class constructors. The state of the child object might not have been initialized yet.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724