Search code examples
javavariablesinheritance

Java Instance Variable Accessibility


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.


Solution

    • 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

    See the JLS for more details

    EDIT: 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... ;-)