Java Reference
In-Depth Information
class LCDemo
{
public static void main(String[] args)
{
EnclosingClass ec = new EnclosingClass();
ec.m(10);
}
}
After instantiating EnclosingClass , Listing 3-13 ' s main() method invokes
m(10) . The called m() method multiplies this argument by 2, instantiates
LocalClass ,whose <init>() methodassignstheargumentandthedoubledvalue
toitspairofinstancefields(inlieuofusingaconstructortoperformthistask),andout-
puts the LocalClass instance fields. The following output results:
10
20
Local classes help improve code clarity because they can be moved closer to where
theyareneeded.Forexample, Listing3-14 declaresan Iterator interfaceandare-
factored ToDoList classwhose iterator() methodreturnsaninstanceofitslocal
Iter class as an Iterator instance (because Iter implements Iterator ).
Listing 3-14. The Iterator interface and the refactored ToDoList class
interface Iterator
{
boolean hasMoreElements();
Object nextElement();
}
class ToDoList
{
private ToDo[] toDoList;
private int index = 0;
ToDoList(int size)
{
toDoList = new ToDo[size];
}
Iterator iterator()
Search WWH ::




Custom Search