vstrimaitis vstrimaitis - 5 months ago 23
Java Question

Output of JAVA program [polymorphism, method overriding]

I am currently learning the JAVA programming language. In my lecturer's notes I found the following code snippet:

class Base{
void g(){
System.out.print("g-Base ");
}
void f(){
System.out.print("f-Base ");
g();
}
}
class Derived extends Base{
public static void main(String[] args) {
Base b = new Derived(); b.f();
}
void g() {
System.out.print("g-Derived ");
}
void f() {
System.out.print("f-Derived "); super.f();
}
}


The question is: what is the output of this program. I compiled and ran it and got: f-Derived f-Base g-Derived
I understand the f-Derived and f-Base parts, but why did it print "g-Derived" in the last step, I thought it should have been "g-Base".

Answer

Let's track the sequence of execution:

  1. Derived#f is called and prints `"f-Derived".
  2. Derived#f then calls super.f(), which means Base#f.
  3. Base#f prints "f-Base".
  4. Base#f then calls g(). Since g() is overriden in Derived, Derived#g is called.
  5. Derived#g prints "g-Derived".