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.
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