Java 中Inner Class的用法(1)

Inner Class得你可以在一个类中把逻辑意义相同的部分放在一起,便于管理。起初学习Inner Class会有些疑惑,下面通过两个示例来说明Inner Class的用法。

1. Outer Class 的成员函数可以像访问其他类一样来访问Inner Class( 来自thinking in java),除此之外,必须用OutClass.InnerClass的形式访问Inner Class(例如main函数)。
   public class Parcel {
class Destination{
private String label;
public Destination(String whereTo){
this.label = whereTo;
}
String readLabel(){
return label;
}
}

public Destination to(String s){
return new Destination(s);
}

public void ship(String dest){
Destination d = to(dest);
System.out.println(d.readLabel());
}

public static void main(String[] args){
Parcel p = new Parcel();
p.ship("Beijing");
Parcel q = new Parcel();
Parcel.Destination d = q.to("ShangHai");
System.out.println(d.readLabel());
}
}

2. Inner Class保存一个指向Outer Class的指针,因此可以访问Outer Class的任何成员。下面的例子同时是一个迭代器模式的例子。

interface Iterator {
public Object next();
public boolean hasNext();
}

public interface Aggregrate {
public Iterator iterator();
}

public class Sequence implements Aggregrate{

private Object[] items;
private int index = 0;

public Sequence(int capacity){
items = new Object[capacity];
}

public void add(Object o){
if(index < items.length){
items[index++] = o;
}
}

private class SequenceIterator implements Iterator{

private int currentIndex = 0;
public boolean hasNext() {
return currentIndex < index;
}

public Object next() {
return items[currentIndex++];
}
}
public Iterator iterator(){
return new SequenceIterator();
}

public static void main(String[] args){
Sequence s = new Sequence(10);
for(int i = 0; i <9; i++){
s.add(Integer.toString(i) + " ");
}
Iterator iter = s.iterator();
while(iter.hasNext()){
String item = (String)iter.next();
System.out.print(item);
}
}

}

你可能感兴趣的:(java)