What are the access levels in Java, and what does each one actually let another class do?
Java has four access levels, and each one says who is allowed to touch a member. The order from the most open to the least open is public, protected, package-private and private.
public class Main {
public static void main(String[] args) {
Account a = new Account("Ada");
System.out.println(a.owner());
}
}
And here is the class with all four levels in it.
package com.example.bank;
public class Account {
public static final String BANK_NAME = "Example Bank";
protected final String owner;
private double balance;
double internalNote; // package-private
public Account(String owner) {
this.owner = owner;
}
public String owner() {
return owner;
}
protected void audit(String line) {
System.out.println(owner + ": " + line);
}
double close() {
this.balance = 0;
return balance;
}
}
So what does each level actually let another class do?
the level who can use it
----------------- ------------------------------------------------
public everybody, from anywhere
protected the same class, the same package, and any
subclass wherever it is
package-private the same class and the same package only
private the same class only
And the detail that people get wrong is protected. It is not the same as package-private. A protected member can also be reached by a subclass, even when the subclass is in a different package. So protected is package-private plus the subclass rule.
And the detail about private is that it is about the class and not the object. So every object of the class can read the private fields of any other object of the same class.
public boolean sameBalance(Account other) {
// This works, because other is an Account.
return this.balance == other.balance;
}
And there is one more thing worth knowing about. The access level of a class itself matters as well. A public class can be used from anywhere. A package-private class can only be used from inside its own package. So the class that holds your public interface has to be public, and the classes that implement it can stay package-private so that nobody uses them by mistake.
So the rule to remember is this. Start with private, and widen it only when something outside really needs it.
The next two questions in this topic are about protected and about the risk of protected members.