java类成员的访问级别
我意识到这是一个非常基本的问题,但却一直困扰着我。 据我了解,如果你在 Java 中声明一个私有字段,那么它在该类之外是不可见的。 如果它受到保护,那么它可用于继承的类和同一包中的任何内容(如果这些定义中的任何一个不正确,请纠正我)。
这是否意味着无法声明一个只能被继承类访问而不能被同一包中的其他非继承类访问的字段?
我知道有很多方法可以解决这个问题,但是在某些情况下您会希望有这种行为吗?
显然,上述问题适用于方法和字段。
非常感谢。
I realise that this is a very basic question, but it is one which has always bothered me. As I understand things, if you declare a field private in Java then it is not visible outside of that class. If it is protected then it is available to inherited classes and anything in the same package (correct me if either of those definitions is incorrect).
Does this mean it is not possible to declare a field that is accessible to only inherited classes and not other non-inherited classes in the same package?
I appreciate that there are ways around this, but are there instances when you would want to have this sort of behaviour?
Obviously the above question applies to methods as well as fields.
Many thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
请参阅: http://java.sun.com/docs/books /tutorial/java/javaOO/accesscontrol.html
套餐> 子类,永远不能有一个字段仅对子类可见,但对同一包中的类不可见。
See: http://java.sun.com/docs/books/tutorial/java/javaOO/accesscontrol.html
Package > Subclasses, you can never have a field only visible by subclasses but not by classes from the same package.
基本上:
更多信息请参见此处。
Basically:
more information here.
是的,Java 的受保护访问在这方面有点奇怪。 我无法立即明白为什么它是可取的。 就我个人而言,它并不困扰我字段,因为我无论如何都不喜欢非私有字段(除了常量),但对于其他成员也是如此。
.NET 根本没有包/命名空间访问可见性的概念,但它有一个替代方案,即程序集(想想“jar 文件” - 不完全相同,但很接近)。 坦率地说,我希望有命名空间和部署单元可见性选项,但似乎我注定要失望......
Yes, Java's protected access is a little bit odd in that way. I can't immediately see why it's desirable at all. Personally it doesn't bother me for fields as I don't like non-private fields anyway (other than constants) but the same is true for other members.
.NET doesn't have the concept of package/namespace access visibility at all, but it has an alternative which is assembly (think "jar file" - not exactly the same, but close). Frankly I'd like to have namespace and deployment-unit visibility options, but it seems I'm doomed to disappointment...