Java Reference
In-Depth Information
public Iterator<String> titleIterator() {
// A local inner class - TitleIterator
class TitleIterator implements Iterator<String> {
int count = 0;
@Override
public boolean hasNext() {
return (count < titleList.size());
}
@Override
public String next() {
return titleList.get(count++);
}
} // Local Inner Class TitleIterator ends here
// Create an object of the local inner class and return the reference
TitleIterator titleIterator = new TitleIterator();
return titleIterator;
}
}
A
TitleList
object can hold a list of book titles. The
addTitle()
method is used to add a title to the list. The
removeTitle()
method is used to remove a title from the list. The
titleIterator()
method returns an Iterator for
the title list. The
titleIterator()
method defines a local inner class called
TitleIterator
, which implements the
Iterator
interface. Note that the
TitleIterator
class uses the private instance variable
titleList
of its enclosing
class. At the end, the
titleIterator()
method creates an object of the
TitleIterator
class and returns the object's
reference. Listing 2-4 shows how to use the
titleIterator()
method of the
TitleList
class.
Listing 2-4.
Using a Local Inner Class
// TitleListTest.java
package com.jdojo.innerclasses;
import java.util.Iterator;
public class TitleListTest {
public static void main(String[] args) {
TitleList tl = new TitleList();
// Add two titles
tl.addTitle("Beginning Java 8");
tl.addTitle("Scripting in Java");
// Get the iterator
Iterator iterator = tl.titleIterator();
// Print all titles using the iterator
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
}
}