Java code snippet output explanation required

Viewed 6045

My code is:

class Foo {
  public int a=3;
  public void addFive() {
    a+=5;
    System.out.print("f ");
  }
}

class Bar extends Foo {
  public int a=8;
  public void addFive() {
    this.a += 5;
    System.out.print("b ");
  }
}

public class TestClass {
  public static void main(String[]args) {
    Foo f = new Bar();
    f.addFive();
    System.out.println(f.a);
  }
}

Output:

b 3

Please explain to me, why is the output for this question "b 3" and not "b 13" since the method has been overridden?

4 Answers
Related