Java Reference
In-Depth Information
Static nested classes serve as a mechanism for defining logically related
types within a context in which that type makes sense. For example, on
page 62 we showed a Permissions class that bears information about a
BankAccount object. Because the Permissions class is related to the con-
tract of the BankAccount classit is how a BankAccount object communicates
a set of permissionsit is a good candidate to be a nested class:
public class BankAccount {
private long number; // account number
private long balance; // current balance (in cents)
public static class Permissions {
public boolean canDeposit,
canWithdraw,
canClose;
}
// ...
}
The Permissions class is defined inside the BankAccount class, making it
a member of that class. When permissionsFor returns a Permissions ob-
ject, it can refer to the class simply as Permissions in the same way it
can refer to balance without qualification: Permissions is a member of
the class. The full name of the class is BankAccount.Permissions . This full
name clearly indicates that the class exists as part of the BankAccount
class, not as a stand-alone type. Code outside the BankAccount class must
use the full name, for example:
BankAccount.Permissions perm = acct.permissionsFor(owner);
If BankAccount were in a package named bank , the full name of the
class would be bank.BankAccount.Permissions (packages are discussed in
Chapter 18 ) . In your own code, you could import the class BankAc-
count.Permissions and then use the simple name Permissions , but you
 
Search WWH ::




Custom Search