到目前为止,内部类似乎还只是一种名字隐藏和组织代码的模式,这些都是很有用的,但还不是最引人注目的,它还有其他的用途。当生成一个内部类的对象时,此对象与制造它的外围对象之间就有一种联系,所以它能访问其外围对象的所有成员,而不需要任何特殊条件。此外,内部类还拥有其他的外围类的所有元素的访问权。
下面例子说明这一点:
1 package innerclasses; 2 3 interface Selector{ 4 boolean end(); 5 Object current(); 6 void next(); 7 } 8 9 public class Sequence { 10 private Object[] items; 11 private int next = 0; 12 public Sequence(int size){ 13 items = new Object[size]; 14 } 15 16 public void add(Object x){ 17 if(next < items.length) 18 items[next++] = x; 19 } 20 private class SequenceSelector implements Selector{ 21 private int i = 0; 22 public boolean end(){ 23 return i == items.length; 24 } 25 public Object current() { 26 // TODO Auto-generated method stub 27 return items[i]; 28 } 29 public void next() { 30 // TODO Auto-generated method stub 31 if(i<items.length) i++; 32 } 33 } 34 35 public Selector selector() 36 { 37 return new SequenceSelector(); 38 } 39 40 public static void main(String[] args){ 41 Sequence sequence = new Sequence(10); 42 for(int i = 0;i < 10;i++) 43 { 44 sequence.add(Integer.toString(i)); 45 } 46 Selector selector = sequence.selector(); 47 while(!selector.end()){ 48 System.out.print(selector.current()+ " "); 49 selector.next(); 50 } 51 52 } 53 }
结果:
0 1 2 3 4 5 6 7 8 9