Java Reference
In-Depth Information
In Chapter 5 we defined the concept of an iterator, using a loop to process all
elements in the collection. Most iterators, including objects of the Scanner class,
are defined using the Iterator interface.
The two primary methods in the Iterator interface are hasNext , which returns
a boolean result, and next , which returns an object. Neither of these methods
takes any parameters. The hasNext method returns true if there are items left to
process, and next returns the next object. It is up to the designer of the class that
implements the Iterator interface to decide the order in which objects will be
delivered by the next method.
We should note that, according to the spirit of the interface, the next method does
not remove the object from the underlying collection; it simply returns a reference to
it. The Iterator interface also has a method called remove , which takes no param-
eters and has a void return type. A call to the remove method removes the object
that was most recently returned by the next method from the underlying collection.
SELF-REVIEW QUESTIONS (see answers in Appendix N)
SR 7.14 What is the difference between a class and an interface?
SR 7.15 Define a Java interface called Nameable . Classes that implement this
interface must provide a setName method that requires a single String
parameter and returns nothing, and a getName method that has no
parameters and returns a String .
SR 7.16 True or False? Explain.
a. A Java interface can include only abstract methods, nothing else.
b. An abstract method is a method that does not have an implementation.
c. All of the methods included in a Java interface definition must be
abstract.
d. A class that implements an interface can define only those methods
that are included in the interface.
e. Multiple classes can implement the same interface.
f. A class can implement more than one interface.
g. All classes that implement an interface must provide the exact
same definitions of the methods that are included in the interface.
7.6 Enumerated Types Revisited
In Chapter 3 we introduced the concept of an enumerated type, which defines a
new data type and lists all possible values of that type. We gave an example that
defined an enumerated type called Season , which was declared as follows:
enum Season {winter, spring, summer, fall}
 
Search WWH ::




Custom Search