public interface Iterator
{
public abstract boolean hasNext();
public abstract Object next();
}
public interface Collection
{
public abstract Iterator iterator();
}
public interface List extends Collection
{
...
}
public class ArrayList implements List
{
public Iterator iterator() {
return new Itr();
}
private class Itr implements Iterator {
public boolean hasNext() {
return xxx;;
}
public E next() {
return xxx;
}
}
}
用法:
//多态
Collection c = new ArrayList();
//添加元素
c.add("hello");
c.add("world");
c.add("java);
Iterator it = c.iterator(); //把Itr返回来了,而Itr实现了Iterator接口。所以,这是多态的体现。
while(it.hasNext())
{
String s = it.next();
System.out.println(s);
}
|
|