Search code examples
javasubtypedynamic-dispatch

Dynamic dispatch in Java


Suppose I have a class A which defines a method bar(). The method bar() calls another method foo(). I then extend A in B and override foo() and do not override bar() (so it gets inherited). Which foo() is being called in these two cases?

A a = new B();
a.bar(); // A or B's foo called?

B b = new B();
b.bar(); // A or B's foo called?

Solution

  • Both uses use B's foo(). A a is just accessing B's methods since B is the instance.

    Think of A a as the interface for the instance, in this case: new B()

    Here's an example (in groovy): http://groovyconsole.appspot.com/script/616002