Access Control
Java has four levels of controlling access to fields, methods, and classes:
public access
Can be accessed by methods of all classes
private access
Can be accessed only by the methods of their own class
protected access
Protected features can be accessed by all subclasses and all classes in the same package.
package access
The default, when no access modifier is given
Can be accessed by all classes in the same package
Good default for classes, but extremely unfortunate for fields
Recommended Access Levels
Instance and static fields: Always private. Exceptions:
public static final constants are useful and safe
Some objects, such as System.out, need to be accessible to all programs (public)
Occasionally, classes in a package must collaborate very closely (give some fields package access); inner classes are usually better
Methods: public or private
Classes and interfaces: public or package
Better alternative to package access: inner classes
In general, inner classes should not be public (some exceptions exist, e.g., Ellipse2D.Double)
Beware of accidental package access (forgetting public or private)
What is a common reason for defining package-visible instance fields?
Answer: Accidentally forgetting the private modifier.
If a class with a public constructor has package access, who can construct objects of it?
Answer: Any methods of classes in the same package.