【发布时间】:2014-09-12 04:51:22
【问题描述】:
我正在做这个学校练习,我不明白为什么以下两种情况会产生不同的结果。有人可以解释为什么在第一种情况下int x 的 A 是 100? C 中的 int x 不是遮蔽了 A 中的 int x 吗?我也在代码中评论了我的问题。非常感谢!
class A { // Case 1
public int x = 1;
public String k() { return "A" + this.x; }
}
class B extends A {
public int x = 10;
}
class C extends B {
public int x = 100;
public String k() { return "C" + this.x; }
}
class TestABC {
public static void main(String[] args) {
A a1 = new C();
C c1 = new C();
}
}
System.out.println(a1.x +"," + c1.x);// It prints out 1, 100.
//However I thought it'd print out 100, 100, as the int x in C shadows int x in A.
另一种情况是
class A1 { //case 2
int x=10;
public void method() {
System.out.print("A:" + this.x + " ");
}
}
class B1 extends A1 {
int x=20;
public void method() {
System.out.print("B:" + this.x + " ");
}
public static void main(String args[]) {
A1 s = new B1();
s.method();// It prints out B: 20.
//What's the difference between this one and a1.x in the previous example?
//Why it prints out the subclass but in the previous code a1.x prints out the parent class?
}
}
【问题讨论】:
标签: java inheritance binding constructor typing