10.2連接到外部類java
一、當生成一個內部類的對象時,此對象與製造它的外圍對象之間就有了一種聯繫,因此它能訪問其外圍對象的全部成員,而不須要任何特殊條件。code
interface Selector { boolean end(); Object current(); void next(); } public class Sequence { private Object [] items; private int next = 0; public Sequence(int size) { items = new Object[size]; } public void add(Object x) { if(next < items.length) items[next++] = x; } private class SequenceSelector implements Selector { private int i = 0; public boolean end() { return i == items.length; } public Object current() { return items[i]; } public void next() { if(i < items.length) i++; } } public Selector selector() { return new SequenceSelector(); } public static void main(String[] args) { Sequence sequence = new Sequence(10); for(int i = 0; i < 10; i++) { sequence.add(Integer.toString(i)); } Selector selector = sequence.selector(); while(!selector.end()) { System.out.print(selector.current() + " "); selector.next(); } } }
(1)要獲取Sequence中的每個對象,能夠使用Selector接口。對象
(2)內部類能夠訪問其外圍類的方法和字段,就像本身擁有似的。接口
(3)內部類自動擁有對其外部類全部成員的訪問權。這是如何作到的呢?it
當某個外圍類的對象建立了一個內部類對象時,此內部類對象一定會祕密的捕獲一個指向那個外圍類對象的引用。class
(4)只有內部類是非static類時才能建立內部類對象。select