我想不出该怎么试。我知道匿名内部类的constructor是直接用花括号括起来即可,如下例:public class Parcel9 {
public Destination
dest(final String dest, final float price) {
return new Destination() {
private int cost;
// Instance initialization for each object:
// Below is the constructor for the anonymouse inner class
{
cost = Math.round(price);
if(cost > 100)
System.out.println("Over budget!");
}
private String label = dest;
public String readLabel() { return label; }
};
}
public static void main(String[] args) {
Parcel9 p = new Parcel9();
Destination d = p.dest("Tanzania", 101.395F);
d.cost100();
System.out.println(d.readLabel());
}
} ///:~而且没办法带参数,可如何定义第二个constructor呢?
public Destination
dest(final String dest, final float price) {
return new Destination() {
private int cost;
// Instance initialization for each object:
// Below is the constructor for the anonymouse inner class
{
cost = Math.round(price);
if(cost > 100)
System.out.println("Over budget!");
}
private String label = dest;
public String readLabel() { return label; }
};
}
public static void main(String[] args) {
Parcel9 p = new Parcel9();
Destination d = p.dest("Tanzania", 101.395F);
d.cost100();
System.out.println(d.readLabel());
}
} ///:~而且没办法带参数,可如何定义第二个constructor呢?
public Destination
dest(final String dest, final float price) {
return new Destination() {
private int cost;
// Instance initialization for each object:
{
cost = Math.round(price);
if(cost > 100)
System.out.println("Over budget!");
}
{
System.out.println("The second constructor!");
} private String label = dest;
public String readLabel() { return label; }
};
}
public static void main(String[] args) {
Parcel9 p = new Parcel9();
Destination d = p.dest("Tanzania", 101.395F);
//d.cost100();
System.out.println(d.readLabel());
}
} ///:~Output是:Over budget!
The second constructor!
Tanzania
你的例子我已看明白了,不过我在书上没查到“匿名内部类的constructor是直接用花括号括起来即可”,真的是这样吗?因为我用匿名内部类从来没用过它的构造器。
还有“用instance initializer(实例初始化)实现的constructor”是什么意思呀?
我初接触这些知识,请指点。
你的例子来自于《thinking in java》,不过这段程序的前面有几段话,楼主显然没有看到。
1:由于匿名内部类没有名称,因而无法给其构造器以任何名字,因此它无法拥有构造器。
2:如果想进行初始化,可以在资料成员定义处进行。对于比较复杂的初始化(例如楼主例子中的if语句),可以用instance initializer的方法来进行初始化。它相当于匿名内部类的构造器。