我想知道在两个java类和之间隐藏字段意味着什么意思在运行代码时产生的输出是什么意思?
I was wondering what it means to say a field is hidden between 2 java classes and what it means when running code in terms of resulting output?
我有一个带有 protected static boolean field = false 的抽象类和一个子类,它有一个具有相同名称但不是静态的布尔字段并设置到 true 。
I have an abstract class with a protected static boolean field = false and a sub class which has a boolean field with the same name but is not static and set to true.
如果我有这个代码:
Superclass d = new subclass();超类中布尔字段的值和布尔字段 in子类?在上面的赋值之后,子类字段是否保留为 false ?
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?
非常感谢
推荐答案static 成员永远不会被覆盖(当然也不是非静态成员)。因为您应该像这样访问它们: ClassName.member 也无需担心隐藏它们。
static members are never overridden (and certainly not by non-static members). And since you should access them like this: ClassName.member there is also no need to worry about hiding them.
在您的情况下,您将访问 Superclass 字段,如下所示: Superclass.field 。以及 Subclass 实例的字段如下: subclass.field 。如果您在 Superclass 变量中有一个 Subclass 实例,如上所示,此代码: d.field 将访问 Superclass 中定义的静态字段,该字段将为 false in你的情况。
In your case, you would access the Superclass field like this: Superclass.field. And the field of a Subclass instance like this: subclass.field. If you have, however a Subclass instance in a Superclass variable like above, this code: d.field will access the static field defined in Superclass, which will be false in your case.
但是这不会改变 Subclass 实例的值,它只是访问错误会员!您可以通过将 d 中的实例放回子类变量并读取字段来验证这一点再次。
But this does not change the value of the Subclass instance, it just accesses the "wrong" member! You can verify this by putting the instance in d back into a Subclass variable and reading field again.
更多推荐
Java字段隐藏
发布评论