今天问题特别多,在看TIJ的内部类时,书中给了这么一例:
//: c08:Parcel9.java
// From 'Thinking in Java, 2nd ed.' by Bruce Eckel
// www.BruceEckel.com. See copyright notice in CopyRight.txt.
// Using "instance initialization" to perform
// construction on an anonymous inner class.public class Parcel9 {
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!");
}
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);
}
} ///:~说{
cost = Math.round(price);
if(cost > 100)
System.out.println("Over budget!");
}
就是实例初始化,在类的定义中,怎么会有这种东西啊?书中的前面似乎也没有出现过。类里面不是除了方法的定义就是域吗?来这么一段就可以当构造函数了?
哪位给说明一下。谢谢
//: c08:Parcel9.java
// From 'Thinking in Java, 2nd ed.' by Bruce Eckel
// www.BruceEckel.com. See copyright notice in CopyRight.txt.
// Using "instance initialization" to perform
// construction on an anonymous inner class.public class Parcel9 {
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!");
}
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);
}
} ///:~说{
cost = Math.round(price);
if(cost > 100)
System.out.println("Over budget!");
}
就是实例初始化,在类的定义中,怎么会有这种东西啊?书中的前面似乎也没有出现过。类里面不是除了方法的定义就是域吗?来这么一段就可以当构造函数了?
哪位给说明一下。谢谢
return new Destination() {
private int cost;
// Instance initialization for each object:
{
cost = Math.round(price);
if(cost > 100)
System.out.println("Over budget!");
}
private String label = dest;
public String readLabel() { return label; }
}; 等价于
class someClass extends(or implements) Destination{
private int cost;
// Instance initialization for each object:
{
cost = Math.round(price);
if(cost > 100)
System.out.println("Over budget!");
}
private String label = dest;
public String readLabel() { return label; }
}return new someClass();
楼主既然在看内部类,为啥就不好好看看啥是内部类
还有一个叫静态出示化块(static initializer)
LZ可以去参考一下Java语言规范的8.6(Instance Initializer)和8.7(Static Initializer)
那里讲得好些