i need someone help with this little code snippet; why is the output: b 3 and not b 13 as expected?
public class Foo{
int a = 3;
public void addFive() { a+=5; System.out.println("f");}
}
class Bar extends Foo{
int a = 8;
public void addFive() { this.a+=5; System.out.println("b");}
public static void main(String[] args) {
Foo f = new Bar();
f.addFive();
System.out.println(f.a);// why b 3 and not b 13 ??
}
}
FooandBarhave two differentafields; Java does not have any notion of field overriding.Calling
f.addFive()calls the derived version of the method (since Java does do method overriding), which modifiesBar.a.However, accessing
f.areturnsFoo.a(sincefis declared asFoo), which was never changed.