What are the four access levels in Java, and exactly what can each one see?
There are four of them, and they are about how much of your class the rest of the program is allowed to see.
public means that anybody can use it. The class, the method or the field can be reached from any package, from any code.
protected means that the code in the same package can use it, and so can any subclass, even a subclass that lives in a different package.
default access, which is also called package-private, means that only the code in the same package can use it. There is no keyword for it, so you leave the access level out altogether.
private means that only the class itself can use it. Not even a subclass in the same package can reach it.
public class Main {
public static void main(String[] args) {
Counter counter = new Counter();
counter.increment();
counter.increment();
System.out.println("count : " + counter.getCount());
}
}
class Counter {
private int count; // only this class
int steps; // only this package
protected String label; // this package and any subclass
public String name; // anybody
void increment() {
this.count = this.count + 1;
this.steps = this.steps + 1;
}
public int getCount() {
return this.count;
}
}
The rule that most people find hard is the protected one, and it is the subject of the next question.
public class Main {
public static void main(String[] args) {
Base base = new Base();
base.showAccessible();
}
}
class Base {
protected String label = "protected label";
public void showAccessible() {
System.out.println("inside the class : " + label);
}
}
The next question in this topic explains the exact rule that governs protected access from another package.