Java实例变量可访问性 [英] Java Instance Variable Accessibility

查看:199
本文介绍了Java实例变量可访问性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java中以下变量的可访问性有何不同?

What is the difference in the accessibility of the following variables in Java?

public class Joe {
    public int a;
    protected int b;
    private int b;
    int c;
}

我最感兴趣的是最后一个人在做什么。

I'm most interested in what the last one is doing.

推荐答案


  • public:对任何人都可读/写

  • protected:read /可写为
    子类的实例,并且来自封闭包

  • private:读/写任何实例类
    和内部或外部(封闭)实例

  • int c:
    package-private,可读/写
    同一个包内的所有类

    • public: read/writable for anyone
    • protected: read/writable for instances of subclasses and from within the enclosing package
    • private: read/writable for any instance of the class and inner or outer (enclosing) instance
    • int c : package-private, read/writable for all classes inside same package
    • 请参阅 JLS 了解更多详情

      编辑:添加了对受保护的评论,说明访问是从在同一个包里,你们是完全正确的。还添加了私人评论。我现在记得......; - )

      Added the comment for protected stating that access is granted from inside same package, you guys are totally right. Also added comment for private. I remember now... ;-)

      这篇关于Java实例变量可访问性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆