匿名内部类和多态结合的易错点
前提:
- 匿名内部类必须定义在方法当中,它是一种特殊的局部内部类(没有名字)
- 匿名内部类必须实现接口或者继承抽象类
interface inter
{
public void show1();
public void show2();
}
class Outer{
public static void main(String[] args)
{
Outer o=new Outer();
o.method();
}
public void method()
{
inter i=new inter()
{
public void show1()
{
System.out.println("show1");
}
public void show2()
{
System.out.println("show2");
}
public void show3()
{
System.out.println("show3");
}
};
i.show3();
}
}
易错点:
- 匿名内部类:inter i=new inter(){};相当于这个匿名内部类向上转型,所以它限制其访问该类的特有的方法。所以程序当中i.show3();是错误的,这相当于与多态的结合。所以匿名内部类当中不能定义特有的方法。
- 匿名内部类不能定义构造函数