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?
You cannot override variables in Java, hence you actually have two
avariables – one inFooand one inBar. On the other handaddFive()method is polymorphic, thus it modifiesBar.a(Bar.addFive()is called, despite static type offbeingFoo).But in the end you access
f.aand this reference is resolved during compilation using known type off, which isFoo. And thereforeFoo.awas never touched.BTW non-final variables in Java should never be public.