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);
}
Asked
Active
Viewed 80 times
0
duffy356
- 3,578
- 3
- 31
- 45
3 Answers
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
- 203,151
- 43
- 392
- 509
1
Because you used Boo
Boo f=new Bar();
reference and fields are not polymorphic
jmj
- 232,312
- 42
- 391
- 431
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.