THE Java™ Programming Language, Fourth Edition

(Jeff_L) #1

5.1.2. Nested Interfaces


Nested interfaces are also always static and again, by convention the static modifier is omitted from the
interface declaration. They serve simply as a structuring mechanism for related types. When we look at
non-static nested classes you will see that they are inherently concerned with implementation issues. Since
interfaces do not dictate implementation they cannot be non-static.


Exercise 5.1: Consider the Attr class and Attributed interface from Chapter 4. Should one of these be a
nested type of the other? If so, which way makes the most sense?


5.2. Inner Classes


Non-static nested classes are called inner classes. Non-static class members are associated with instances of a
classnon-static fields are instance variables and non-static methods operate on an instance. Similarly, an inner
class is also (usually) associated with an instance of a class, or more specifically an instance of an inner class
is associated with an instance of its enclosing classthe enclosing instance or enclosing object.


You often need to closely tie a nested class object to a particular object of the enclosing class. Consider, for
example, a method for the BankAccount class that lets you see the last action performed on the account,
such as a deposit or withdrawal:


public class BankAccount {
private long number; // account number
private long balance; // current balance (in cents)
private Action lastAct; // last action performed


public class Action {
private String act;
private long amount;
Action(String act, long amount) {
this.act = act;
this.amount = amount;
}
public String toString() {
// identify our enclosing account
return number + ": " + act + " " + amount;
}
}


public void deposit(long amount) {
balance += amount;
lastAct = new Action("deposit", amount);
}


public void withdraw(long amount) {
balance -= amount;
lastAct = new Action("withdraw", amount);
}
// ...
}


The class Action records a single action on the account. It is not declared static, and that means its
objects exist relative to an object of the enclosing class.


The relationship between an Action object and its BankAccount object is established when the Action

Free download pdf