vstrimaitis vstrimaitis - 1 year ago 87
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 ");
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 Source

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".
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download