请参阅下面的代码,其中方法print
被覆盖但变量a
没有。为什么允许在子类中声明重复变量?
class B {
int a = 10;
public void print() {
System.out.println("inside B superclass");
}
}
class C extends B {
int a = 20;
public void print() {
System.out.println("inside C subclass");
}
}
public class A {
public static void main(String[] args) {
B b = new C();
b.print(); // prints: inside C subclass
System.out.println(b.a); // prints superclass variable value 10
}
}