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.
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.
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... ;-)
And all of these are compile time protections, they can be readily overridden through reflection at runtime.
I try to avoid package level access completely (the last access you mention).
I like to keep classes self-contained. If another class needs access to something in my class it should be public (and it should by a method, not an attribute). Otherwise I feel you've broken encapsulation, as explained in Abstraction VS Information Hiding VS Encapsulation.
Sorry for answering corrections to one previous answer but I don't have enough reputation to modify directly...
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).