访问子类中的隐藏字段
Accessing a hidden field in a subclass
根据以下引用,我希望看到 overriden nullWhosebug
而不是 overriden nullnull
。我错过了什么?
Within a class, a field that has the same name as a field in the superclass hides the superclass's field, even if their types are different.
class A {
public static void main(String[] args) {
new B("message is here");
}
protected int i = 13;
public void print() { System.out.println("Hello"); }
public A() { i = 13; print(); }
}
class B extends A {
private String i = "Whosebug";
private String msg;
public void print() { System.out.println("overriden " + msg + i); }
public B(String msg) { super(); this.msg = msg; }
}
What point did I miss?
print()
被 A
构造函数调用,并且在 调用 B
中的字段初始值设定项之前执行 .有关 class 实例创建表达式如何执行的详细信息,请参阅 JLS 15.9.4。
所以是的,它使用了 B.i
变量,但该变量还没有 Whosebug
的值。如果你要从构造函数中删除 print()
调用并只写 new B("message is here").print()
那么你会看到“overriden nullWhosebug”。
根据以下引用,我希望看到 overriden nullWhosebug
而不是 overriden nullnull
。我错过了什么?
Within a class, a field that has the same name as a field in the superclass hides the superclass's field, even if their types are different.
class A {
public static void main(String[] args) {
new B("message is here");
}
protected int i = 13;
public void print() { System.out.println("Hello"); }
public A() { i = 13; print(); }
}
class B extends A {
private String i = "Whosebug";
private String msg;
public void print() { System.out.println("overriden " + msg + i); }
public B(String msg) { super(); this.msg = msg; }
}
What point did I miss?
print()
被 A
构造函数调用,并且在 调用 B
中的字段初始值设定项之前执行 .有关 class 实例创建表达式如何执行的详细信息,请参阅 JLS 15.9.4。
所以是的,它使用了 B.i
变量,但该变量还没有 Whosebug
的值。如果你要从构造函数中删除 print()
调用并只写 new B("message is here").print()
那么你会看到“overriden nullWhosebug”。