匿名内部类----应用

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 {

    public 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();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值