访问修饰符和隐藏 Java 字段
这是问题的后续:“java访问修饰符和覆盖”。然而,前者通常处理 Java 方法。为什么 Java 字段具有灵活性?我们可以在继承类中缩小或扩大它们的可见性,而不能使用“重写”或“隐藏”方法。
This is a follow-up to the question: "java access modifiers and overriding". The former generally deals with Java methods however. Why the flexibility with Java fields? We can narrow or widen the visibility with their respect in an inherited class whereas can't with an 'overridden' nor 'hidden' method.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您从一开始就不会覆盖字段 - 您总是隐藏它们。字段不是多态的...换句话说,如果您编写:
并且
Superclass
和Subclass
都声明一个名为field
的字段,它将无论如何总是使用超类,因为这是编译器可以“看到”的全部内容。就我个人而言,无论如何我都会尝试将变量保持私有......
You never override fields to start with - you're always hiding them. Fields aren't polymorphic... in other words, if you write:
and both
Superclass
andSubclass
declare a field calledfield
, it will always use the superclass one anyway, because that's all the compiler can "see".Personally I try to keep my variables private anyway...
您不能通过扩展另一个类中的字段来将其私有化。当您在子类中创建新字段时,您只是隐藏了超类字段。
You cannot make a field in another class go private by extending it. When you make a new field in a sub class you are just hiding the super class field.