When you create an inner class, an object of that inner class contains an implicit link to the enclosing object that made it. Through this link, it can access the members of that enclosing object, without any special qualifications.
for example:
// innerclasses/Sequence.java
// (c)2017 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
// 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;
@Override
public boolean end() {
return i == items.length;
}
@Override
public Object current() {
return items[i];
}
@Override
public void next() {
if (i < items.length) i++;
}
}
public Selector selector() {// returns a reference to an inner class SequenceSelector
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
*/
Above is an example of the Iterator design pattern.
Note that each of the methods—end(), current(), and next()—refers to items, a reference that isn’t part of SequenceSelector, but is instead a private field in the enclosing class. However, the inner class can access methods and fields from the enclosing class as if it owned them.
references:
1. On Java 8 - Bruce Eckel
2. https://github.com/wangbingfeng/OnJava8-Examples/blob/master/innerclasses/Sequence.java

本文通过一个具体的Java代码示例,深入探讨了内部类的使用方式及其如何访问外部类的成员变量,同时展示了迭代器设计模式的实现。内部类能够无缝访问外部类的字段和方法,而无需任何特殊限定,这为实现如迭代器等功能提供了便利。
1331

被折叠的 条评论
为什么被折叠?



