0
class Boo {
    public int a = 3;

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

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

public static void main(String[] args) {
    Boo f = new Bar();
    f.addFive();
    System.out.println(f.a);
}
duffy356
  • 3,678
  • 3
  • 32
  • 47

3 Answers3

3

You don't override the instance fields, but only hide them. So, when you access an instance field on a Boo reference, you will get the one declared in Boo class only.

And when you increment the a in the Bar constructor:

this.a += 5;

It is incrementing the a declared in Bar, since it is hiding the field a declared in Boo.

Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
1

Because you used Boo

Boo f=new Bar();

reference and fields are not polymorphic

jmj
  • 237,923
  • 42
  • 401
  • 438
0

The field a in Bar is shadowing field a in Boo. It's a separate field, but because it has the same name, you must reference the field in Boo by super.a to reach it from Bar.

This previous question covers shadowing well.

Community
  • 1
  • 1
Bohemian
  • 412,405
  • 93
  • 575
  • 722