请参阅下面的代码,其中的方法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
}
}
慕婉清6462132
相关分类