从外围类的方法中创建内部类的引用:OuterClassName.InnerClassName
When you create an inner class, an object of that inner class has a link to the enclosing object(外围对象)that made it , and so it can access the members of that enclosing object—without any special qualifications. 即内部类可以访问外围对象的的所有成员。
package innerclasses;
// Holds a sequence of Objects.
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();
}
}
} /* Output:
0 1 2 3 4 5 6 7 8 9
*///:~
可以看出,内部类SequenceSelector的3个方法访问了外围类的私有字段items。
此外,Selector接口是迭代器模式(Iterator Pattern)。Selector接口可以检查是否到了末尾了(end( ))、访问当前对象(current( ))、以及移动到Sequence中的下一个对象(next ())。
在内部类的方法中生成外围类对象的引用:OuterClassName.this
在外围类的方法中创建内部类:OuterClassRefer.new
内部类可以出现在方法内部,也可以出现在如If这样的语句中。