and interfaces in a class: nested classes and interfaces allow you to associate types that are strongly related to
an interface inside that interface. For example, a class that was used only to return multiple values from an
interface's method could be represented as a nested class in that interface:
interface Changeable {
class Record {
public Object changer;
public String changeDesc;
}
Record getLastChange();
// ...
}
The method getLastChange returns a Changeable.Record object that contains the object that made
the change and a string describing the change. This class has meaning relative only to the Changeable
interface, so making a top-level class not only is unnecessary but would also separate it from the context of its
use. As a nested class it is tightly bound to its origin and context, but it is a normal class in every other regard.
Another use for a nested class within an interface is to define a (partial or complete) default implementation
for that interface. A class that implements the interface could then choose to extend the default
implementation class or to forward method invocations to an instance of that class.
Any class or interface nested inside an interface is public and static.
5.6.1. Modifiable Variables in Interfaces
We mentioned on page 121 that if you need shared, modifiable data in an interface, then a nested class is a
simple way of achieving this. Declare a nested class whose fields hold the shared data, and whose methods
provide access to that data, then maintain a reference to an instance of that class. For example:
interface SharedData {
class Data {
private int x = 0;
public int getX() { return x; }
public void setX(int newX) { x = newX; }
}
Data data = new Data();
}
Now all implementors and users of SharedData can share common state via the data reference.
5.7. Implementation of Nested Types
How the compiler and runtime system deal with nested types would ideally be transparent to the programmer.
Unfortunately, this is not quite the case. Nested types were added as a language extension, and that extension
had to maintain compatibility with older Java virtual machines. Consequently, nested types are implemented
in terms of a source code transformation that the compiler applies.