I have these classes:
class A {
public void f() { System.out.println("f() in A"); }
public void g() { System.out.println("g() in A"); f(); }
}
class B extends A {
public void f() { System.out.println("f() in B"); }
}
Why does
B b = new B();
A a = b;
a.g();
print out this
g() in A
f() in B
and not
g() in A
f() in A
Is there something I am missing?
This is because Java uses dynamic dispatch by default (and forcibly) on methods of classes.
This feature makes sure that, when a method is called, the most specialized version of it it is chosen to be executed. In your case, since B extends A, it means that public void f() implementation of B is more specialized than the one of A. So although A a is statically of type A, it's dynamically of type B and that method is chosen.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With