匿名内部类,没有名字的内部类。可以是实体类,也可以是接口。
public
class
Demo {
public
static
void
main(String[] args) {
Person p =
new
Person() {
public
void
eat() {
System.out.println(
"eat something"
);
}
};
p.eat();
}
}
下述代码也是匿名内部类
return new Contents() {
private int i = 11;
public int value() { return i; }
};
这两段代码可以认为是一个意思
class MyContents extends Contents {
private int i = 11;
public int value() { return i; }
}
return new MyContents();
若试图定义一个匿名内部类,并想使用在匿名内部类外部定义的一个对象,则编译器要求外部对象为final属性。假如需要采取一些类似于构建器的行动。假如需要采取一些类似于构建器的行动,我们可以在实例初始化模块中,一个实例初始化模块就是一个匿名内部类的构建器。
下属代码,匿名内部类使用的dest,price必须是final的。{}中包起来的是一个实例初始化模块,但是他是在匿名内部类中,实例初始化模块实在类new新对象的时候才走,匿名内部类无法new对象,因此没起到类初始化模块。但是在匿名内部类里会走实例初始化模块,就起到了构建器的作用。
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);
}
}