Java Reference
In-Depth Information
1 package weiss.ds;
2
3 public class MyContainer
4 {
5 Object [ ] items;
6 int size;
7
8 public Iterator iterator( )
9 { return new MyContainerIterator( this ); }
10
11 // Other methods not shown.
12 }
figure 15.3
The MyContainer class
from Section 6.2
public static void main( String [ ] args )
figure 15.4
main method to
illustrate iterator
design from
Section 6.2
1
{
2
MyContainer v = new MyContainer( );
3
4
5
v.add( "3" );
v.add( "2" );
6
7
8
System.out.println( "Container contents: " );
Iterator itr = v.iterator( );
9
while( itr.hasNext( ) )
10
System.out.println( itr.next( ) );
11
}
12
This design hides the iterator class implementation because MyContainerIterator
is not a public class. Thus the user is forced to program to the Iterator interface
and does not have access to the details of how the iterator was implemented—
the user cannot even declare objects of type weiss.ds.MyContainerIterator .
However, it still exposes more details than we usually like. In the MyContainer
class, the data are not private, and the corresponding iterator class, while not
public, is still package visible. We can solve both problems by using nested
classes: We simply move the iterator class inside of the container class. At that
point the iterator class is a member of the container class, and thus it can be
declared as a private class and its methods can access private data from
MyContainer . The revised code is illustrated in Figure 15.5, with only a stylis-
tic change of renaming MyContainerIterator as LocalIterator . No other
changes are required; however the LocalIterator constructor can be made
private and still be callable from MyContainer , since LocalIterator is part of
MyContainer .
 
Search WWH ::




Custom Search