当生成一个内部类的对象时,此对象与制造它的外围对象就有了一种联系。所以其能访问
其外围对象的所有成员,而不需要任何特殊条件。此外,内部类还拥有其外围类的所有元素的
访问权。
在拥有外部类对象之前是不可能创建内部类对象的。这是因为内部类对象会暗暗地连接到它的外部类对象上。
但是,如果你创建时嵌套类(静态内部类),那么它就不需要对外部对象的引用。
class="java">
public class DotThis {
void f() {
System.out.println("DotThis.f()");
}
public class Inner {
public DotThis outer() {
return DotThis.this;
}
public void say() {
System.out.println("inner class");
}
}
public Inner inner() {
return new Inner();
}
public static void main(String[] args) {
DotThis dotThis = new DotThis();
DotThis.Inner inner = dotThis.inner();
inner.outer().f();
// 创建内部类对象
DotThis.Inner dni = dotThis.new Inner();
dni.say();
}
}
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() {
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.println(selector.current() + " ");
selector.next();
}
}
}
public class Parcel4 {
private class PContents implements Contents {
private int i = 11;
@Override
public int value() {
return i;
}
}
protected class PDestination implements Destination {
private String label;
private PDestination(String whereTo) {
this.label = whereTo;
}
@Override
public String readLabel() {
return label;
}
}
public Destination destination(String s) {
return new PDestination(s);
}
public Contents contents() {
return new PContents();
}
}
匿名内部类
public class Prac17 {
public Contents contents() {
return new Contents() {
private int i = 11;
@Override
public int value() {
return i;
}
};
}
public static void main(String[] args) {
Prac17 prac17 = new Prac17();
Contents c = prac17.contents();
}
}