private server members, while other private members remain hidden. Such selective access may be offered to a client regardless of the package in which it resides, and
is visible only to a client that acquires the privileged access.Essentially, the Access Control pattern can make a non-inner class (Client) behave exactly like an inner class of Server. On the other hand, this virtual inner class differs from a true inner class in that you can design it to see only some Server members, but not others (a true inner class of Server can always see everything inside of Server).
The Access Control pattern used in this article accomplishes the following:
Consider the following classes:
public class Server {
void serverMethod() {
}
}
public class Client {
void clientMethod() {
serverMethod();
}
}
Using Java's built-in access control, you may declare serverMethod() public, protected, friendly (absent access specifier), or private. The clientMethod() has the following corresponding degrees of access:
public void serverMethod()...: The clientMethod() compiles regardless of which package Client resides in, and regardless of whether Client is a Server subclass.
protected void serverMethod()...: The clientMethod() compiles only if Client resides in the same package as Server, or if Client extends Server.
void serverMethod()...: The clientMethod() compiles only if Client resides in the same package as Server.
private void serverMethod()...: The clientMethod() won't compile; only code residing within the Server class can access serverMethod().
There are several situations in which you might want to grant member access only to certain other classes.
Suppose a given class needs many inner classes. You can define any number of inner classes within a class, but that makes for large class files that are difficult to read and maintain. I've encountered this situation with graphics programming, where editable shapes accumulate a dizzying variety of inner classes for responding to a corresponding variety of editing events (usually transmitted to the shape in the form of mouse and/or key events). It may be convenient to turn each inner class into a regular class (defined in its own file), and mimic the inner class behavior by granting access to the appropriate private fields and methods of the original outer class. In this case, you want to grant such access only to those classes intended to behave like the original outer class's inner classes.