package main;
class F {
void f() {
System.out.print("F.f() ");
this.g();
}
void g() {
System.out.print("F.g() ");
}
}
class Fbis extends F {
void f() {
System.out.print("Fbis.f() ");
this.g();
}
void g() {
System.out.print("Fbis.g() ");
super.f();
}
}
public class Main {
public static void main(String[] args) {
F f = new Fbis();
((F) f).f();
}
}
Hi, I’m trying to understand why the g() function in the F class is never called.
This code compiles and runs but leads to an infinite loop that show this:
Fbis.f() Fbis.g() F.f() Fbis.g() F.f() Fbis.g() F.f() Fbis.g() F.f() Fbis.g() F.f() Fbis.g() F.f() Fbis.g() F.f() Fbis.g() F.f() ...
So what happens, is that Fbis.f is called, which calls Fbis.g, which calls F.f but instead of calling F.g, F.f calls Fbis.g.
Basically, that is how inheritance works. The
Fbisclass overrides theg()method so for any instance ofFbiscallingg()will run the code from theFbisclass, even if this called from within theFclass itself.This is usually desirable behaviour. For example, imagine a
delete()method. In a parent class this does some clean up when the object is deleted by your application. In the child class it does extra clean-up specific for this child. You would want the extra clean up to be done wheneverdelete()was called, even if this was from within the parent class.