匿名内部类----应用

来源:互联网 发布:快手特效视频软件 编辑:程序博客网 时间:2024/06/06 09:55
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();    }}
原创粉丝点击