Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java superclass calls subclass method

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?

like image 727
pippo Avatar asked Apr 11 '26 07:04

pippo


1 Answers

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.

like image 127
Jack Avatar answered Apr 12 '26 20:04

Jack



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!