Java Field Hiding
我想知道说一个字段隐藏在 2 个 java 类和
根据结果??输出运行代码意味着什么?
我有一个带有
它有一个同名但不是静态的布尔字段并设置为
如果我有这个代码:
1 | Superclass d = new subclass(); |
超类中的布尔字段和布尔字段的值是什么
在子类中?在上述分配之后,子类字段是否保持为
-
Java 语言规范
If the class declares a field with a certain name, then the declaration of that field is said to hide any and all accessible declarations of fields with the same name in superclasses, and superinterfaces of the class.
A hidden field can be accessed by using a qualified name if it is
static , or by using a field access expression that contains the keywordsuper or a cast to a superclass type.在 http://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html 中查看更多信息
-
示例代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18class A {
static int field;
}
class B extends A {
int field;
void doSomething() {
System.out.println(super.field); // From A
System.out.println(field); // From B
}
}
class Main {
public static void main(String[] args) {
B b = new B();
System.out.println(b.field); // From B
System.out.println(((A) b).field); // From A
System.out.println(A.field); // From A
}
}
在您的情况下,您可以像这样访问
但这不会改变
what would be the value of the boolean field in the superclass and the
boolean field in the subclass?
超类中
Does subclass field stay as FALSE after the assignment above?
没有。您不能覆盖 Java 中的静态变量。本质上发生的是子类中的定义隐藏了超类中声明的变量。
有关一个很好的示例和解释,请参阅 SO Question
我还建议您自己尝试一下,看看会发生什么。