while preparing myself for OCJP exam i stumbled upon one question i am unable to wrap my mind around. Here's (a bit modified by me) code from a question:
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() {
a += 5;
System.out.print("b ");
}
}
public class TestInheritance {
public static void main(String [] args) {
// part 1
Foo f = new Bar();
f.addFive();
System.out.println(f.a);
// part 2
Bar b = new Bar();
b.addFive();
System.out.println(b.a);
}
}
and the output is:
b 3
b 13
Part 2 i can understand. Nothing surprising here. However part 1 does not let me sleep at night. I understand why Bar.addFive was run but why in part 1 f.a prints Foo.a when I used new Bar() to instantiate an object? It looks like inheritance works quite different for methods than for variables. What am i missing here to understand that concept? What am I failing in?