Destination 从哪里来的呢?我想可能的意图是不是:
class Destination{}
public class Parcel8 {
public Destination dest(final String dest) {
return new Destination() {
private String label = dest;
public String readLabel() { return label; }
};
}
public static void main(String[] args) {
Parcel8 p = new Parcel8();
Destination d = p.dest("Tanzania");
}
}
这里的:
return new Destination() {
private String label = dest;
public String readLabel() { return label; }
};
相当于:
class S extends Destination{
private String label = dest;
public String readLabel() { return label; }
}
return new S();有访问修饰符,作用和成员变量一样。
class Destination{}
public class Parcel8 {
public Destination dest(final String dest) {
return new Destination() {
private String label = dest;
public String readLabel() { return label; }
};
}
public static void main(String[] args) {
Parcel8 p = new Parcel8();
Destination d = p.dest("Tanzania");
}
}
这里的:
return new Destination() {
private String label = dest;
public String readLabel() { return label; }
};
相当于:
class S extends Destination{
private String label = dest;
public String readLabel() { return label; }
}
return new S();有访问修饰符,作用和成员变量一样。
书中是在强调:在匿名内部类的方法中使用外部定义的对象作为参数时,一定要加上final。然后给出了这个例子程序。但我发现执行错误。
等待其他的解释。
H:\TIJ-3rd-edition-code\c08>type Des*.javaDestination.java
//: c08:Destination.java
// From 'Thinking in Java, 3rd ed.' (c) Bruce Eckel 2002
// www.BruceEckel.com. See copyright notice in CopyRight.txt.
public interface Destination {
String readLabel();
} ///:~H:\TIJ-3rd-edition-code\c08>