Java字段隐藏

编程入门 行业动态 更新时间:2024-10-28 22:24:19
本文介绍了Java字段隐藏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想知道在两个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字段隐藏

本文发布于:2023-06-05 01:15:16,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/508845.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字段   Java

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!