Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Instance Variable Accessibility [duplicate]

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.

like image 659
Claudiu Avatar asked Dec 17 '22 10:12

Claudiu


2 Answers

  • 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... ;-)

like image 50
Daniel Hiller Avatar answered Dec 27 '22 04:12

Daniel Hiller


Sorry for answering corrections to one previous answer but I don't have enough reputation to modify directly...

  • public - read/writable for anyone
  • protected - read/writable for instances subclasses and all classes inside same package
  • int c : package-private, read/writable for all classes inside same package
  • private - read/writable for any member of that class itself and inner classes (if any)

It is better to order the access modifiers this way, from the broadest access (public) to the narrowest (private), knowing that when going from narrow to broad, you don't lose any possibilities.

That's particularly important for "protected", where it is often misunderstood that classes in the same package can also access protected members of a class (not only its subclasses).

like image 29
jfpoilpret Avatar answered Dec 27 '22 04:12

jfpoilpret