Reputation: 617
I have a question about java syntax. I've found sample program.
public class Main {
public static void main(String[] args) {
BookShelf bookShelf = new BookShelf(2);
bookShelf.appendBook(new Book("around 80 Days"));
bookShelf.appendBook(new Book("trivial solution"));
Iterator it = bookShelf.iterator();
}
}
This is compiled with following interface.
public interface Iterator {
public abstract boolean hasNext();
public abstract Object next();
}
in this program, is 'Iterator' class or type? If it is class, 'new' is needed to create instance like following sentence.
Iterator it = new Iterator();
Otherwise, Is 'Iterator' type? Is interface used as type? thank you.
Upvotes: 2
Views: 109
Reputation: 7047
Iterator is an interface. The most common way for a class to expose an iterator is by implementing Iterable which again is an interface.
Iterator provides you a mechanism by which you can step through all members in a collection.
see http://docs.oracle.com/javase/7/docs/api/java/util/Iterator.html for a description of the Iterator.
see http://docs.oracle.com/javase/7/docs/api/java/lang/Iterable.html For the iterable interface.
Iterator is a design pattern first mentioned in the GOF Book. (I believe)
Also please note you can't create a new iterator just by itself. It does need an implementation to run. It is usually given by a given class (BookShelf) in your example as that class knows how to step through it's internal structures.
As it is an interface it cannot be declared using the new operator. However the concrete implementation of it can be.
Upvotes: 1