请解释一下为什么当我编译这段代码的结果是0?怎么会这样 ?方法继承
class Parentt {
int x = 0;
public void printX() {
System.out.println(x);
}
}
class Child1 extends Parentt {
int x = -1;
}
public class Foo {
public static void main(String[] args) {
new Child1().printX();
}
}
因为你在阴影'Parentt' –
击败我的变量。通常编译不会返回一个数字。但是如果你执行它,你将会从Parentt打印x的值,因为Child1有它自己的副本(因为你再次声明它),这是从Parentt不可见的。 –