The getA()
method is defined in the superclass only, and can only access members of the superclass. It cannot know about the a
of the subclass, so the a
of the subclass cannot shadow it.
Whether the member a
of the subclass is private or public is not relevant. You will see the same behavior if you declare a
to be private in the child class.
Update: Here is an attempt to answer the more general question: How are members which are defined in both parent and subclasses resolved?
Consider the following extension of the OP's example:
class A {
public int a = 10;
public int getA() {
return a;
}
public void setA(int a) {
this.a = a;
}
}
class B extends A {
public int a = 20;
}
class C extends B {
public int getA() {
return a;
}
}
public class Demo {
public static void main(String args[]) {
B a = new B();
System.out.println(a.getA());
C c = new C();
System.out.println(c.getA());
}
}
Here, we see the output 10
and 20
, which implies that class C
's getA()
method is reading class B's version of a
.
Now let us see what happens if we make B
's version of A
private.
class B extends A {
private int a = 20;
}
If we try to compile, we will get a compiler error:
Demo.java:18: error: a has private access in B
The experiment above seems to suggest that each class will attempt to resolve a
by looking at either itself or go up the class hierarchy until it finds the first a
. If that a
is visible to it (meaning public
or protected
), then it will return it. If that a
is not visible, then it will simply not compile.