Assume that I have these three classes:
class Foo {
void fn() {
System.out.println("fn in Foo");
}
}
class Mid extends Foo {
void fn() {
System.out.println("fn in Mid");
}
}
class Bar extends Mid {
void fn() {
System.out.println("fn in Bar");
}
void gn() {
Foo f = (Foo) this;
f.fn();
}
}
public class Trial {
public static void main(String[] args) throws Exception {
Bar b = new Bar();
b.gn();
}
}
Is it possible to call a Foo
's fn()
? I know that my solution in gn()
doesn't work because this
is pointing to an object of type Bar
.
It's not possible in Java. You can use super
but it always uses the method in immediate superclass in type hierarchy.
Also note that this:
Foo f = (Foo) this;
f.fn();
is the very definition of polymoprhism how virtual call works: even though f
is of type Foo
, but at runtime f.fn()
is dispatched to Bar.fn()
. Compile-time type doesn't matter.