java类成员的访问级别

发布于 2024-07-12 09:05:05 字数 272 浏览 12 评论 0原文

我意识到这是一个非常基本的问题,但却一直困扰着我。 据我了解,如果你在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

逆流 2024-07-19 09:05:05

请参阅: 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.

脸赞 2024-07-19 09:05:05

基本上:

  • private:只能由类访问。
  • public:任何类都可以访问。
  • protected:可由类、所有继承的类和当前包的类(已编辑)访问。
  • 未定义范围:可由当前包的所有类访问。

更多信息请参见此处

Basically:

  • private: Accessible only by the class.
  • public: Accessible by any class.
  • protected: Accessible by the class, all inherited classes and the classes of the current package (edited).
  • no scope defined: Accessible by all classes of the current package.

more information here.

心奴独伤 2024-07-19 09:05:05

是的,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...

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文