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
superbut it always uses the method in immediate superclass in type hierarchy.Also note that this:
is the very definition of
polymoprhismhow virtual call works: even thoughfis of typeFoo, but at runtimef.fn()is dispatched toBar.fn(). Compile-time type doesn’t matter.