Using the Iterator
interface allows any class that implements its methods to act as iterators. The notion of an interface in Java is to have, in a way, a contractual obligation to provide certain functionalities in a class that implements
the interface, to act in a way that is required by the interface. Since the contractual obligations must be met in order to be a valid class, other classes which see the class implements
the interface and thus reassured to know that the class will have those certain functionalities.
In this example, rather than implement the methods (hasNext(), next(), remove()
) in the LinkedList
class itself, the LinkedList
class will declare that it implements
the Iterator
interface, so others know that the LinkedList
can be used as an iterator. In turn, the LinkedList
class will implement the methods from the Iterator
interface (such as hasNext()
), so it can function like an iterator.
In other words, implementing an interface is a object-oriented programming notion to let others know that a certain class has what it takes to be what it claims to be.
This notion is enforced by having methods that must be implemented by a class that implements the interface. This makes sure that other classes that want to use the class that implements the Iterator
interface that it will indeed have methods that Iterators should have, such as hasNext()
.
Also, it should be noted that since Java does not have multiple inheritance, the use of interface can be used to emulate that feature. By implementing multiple interfaces, one can have a class that is a subclass to inherit some features, yet also "inherit" the features of another by implementing an interface. One example would be, if I wanted to have a subclass of the LinkedList
class called ReversibleLinkedList
which could iterate in reverse order, I may create an interface called ReverseIterator
and enforce that it provide a previous()
method. Since the LinkedList
already implements Iterator
, the new reversible list would have implemented both the Iterator
and ReverseIterator
interfaces.
You can read more about interfaces from What is an Interface? from The Java Tutorial from Sun.