您的位置:首页 > 其它

匿名内部类----应用

2017-10-17 10:56 84 查看
interface Inter6
{
void show1();
void show2();
}
class Outer6
{//非匿名内部类
//  class Inner implements Inter
//  {
//      public void show1() {
//
//      }
//      public void show2() {
//
//      }
//  }

public void method() {
//      Inner in = new Inner();
//      in.show1();
//      in.show2();
//匿名内部类 但是如果我想多次调用 比如两次调用里面的show1和show2
//两次调用new两次太麻烦了 所以可以 Inter6 in = new Inter6()
new Inter6() {

public void show2() {

}

public void show1() {

}
};
in.show1();
in.show2();
}
}
/*
通常的使用场景之一:
当函数参数是接口类型时,而且接口中的方法不超过三个。
可以用匿名内部类作为实际参数作为传递,
*/
//原先的操作:
/*public class InnerClassDemo5 {

public static void main(String[] args) {
// TODO Auto-generated method stub
show(new InterImpl6());
}
//使用接口
public static void show(Inter6 in) {
in.show1();
in.show2();
}
}

//实现接口
class InterImpl6 implements Inter6
{
public void show1(){}
public void show2(){}
}*/
//现在的操作:
public class InnerClassDemo5 {

pu
4000
blic static void main(String[] args) {
// TODO Auto-generated method stub
show(new Inter6(){
public void show1(){}
public void show2(){}
});//直接new然后在里面覆盖
}
//使用接口
public static void show(Inter6 in) {
in.show1();
in.show2();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: