0

I apologize if I am duplicating a question. I am struggling to understand something. Any help would be appreciated! We have 3 classes, A, B and C as follows:

public class A {
    public void func() {System.out.println("A's func");}
}

public class B extends A{
    private void f() {System.out.println("B's f");}
    public void foo() {
        f();
        func();
    }
}

public class C extends B {
    public void f() {System.out.println("C's f");}
    public void func() {System.out.println("C's func");}
    public static void main(String[] args) {
        B b = new C();
        b.foo();
    }
}

C's main will print:

B's f
C's func

And I am struggling to understand why the output isn't:

C's f
C's func

Since foo doesn't exist in C, B's foo method is invoked. But then it calls f. As I see it, b's dynamic type is C, so why isn't C's f method isn't invoked? I figured that it has to do something with visibility of B's f method. It's private, and so it's invoked relative to the static type of b. So what I am not getting here, why B's method got the precedence? After all, when it invoked the func method in foo, it did call C's funct method...

Thank you!

RealSkeptic
  • 33,993
  • 7
  • 53
  • 79
  • 3
    Private methods are not inheritable. You can't override them. – RealSkeptic Jan 29 '20 at 11:12
  • If you intend to override a method, use the `@Override` annotation. That way, the compiler will tell you when it does in fact not override anything (as in your case). https://stackoverflow.com/questions/94361/when-do-you-use-javas-override-annotation-and-why – Thilo Jan 29 '20 at 11:15
  • @RealSkeptic thank you for the reply. I know that privatem ethods are not inheritable and you can't override them. But when B's foo() method was invoked it calls f(). From what I know its equivalent to this.f(); which is equivalen to b.f(); And from dynamic dispatch shouldn't C's method be invoked? – Charles Carmichael Jan 29 '20 at 11:17
  • 1
    No, because private methods do not take part in dynamic dispatch. – Thilo Jan 29 '20 at 11:18
  • @RealSkeptic Ahhhhhhhh now I get it – Charles Carmichael Jan 29 '20 at 11:20

0 Answers0