匿名内部类是局部内部类的一种特殊情况,它本身无名,当然也就没有构造器了。申明它时必须修同时建立匿名内部类对象。且用的是父类名或其实现的接口名称。由于它在方法中申明。所以可以把它看成实现了某种功能的代码块(被匿名内部类封装)。要调用匿名内部类方法,可将其向上转型成父类或接口来使用。所以上面的代码就好理解了。show(new Inter()
{
public void method()
{
System.out.println("method show run");
}
});
}//在方法中定义 匿名内部类。(
public static void show(Inter in)
{
in.method();
}
}//传入 匿名内部类引用,并调用其方法。
上面的方法也可以写成如下形式
public static void show(){
new Inter() { public void method()
{
System.out.println("method show run");
}
}.method();}
|