Java——多态——匿名内部类

Java——多态——匿名内部类

案例1:

//匿名内部类
interface Animal15 {
          
   
    void shout();
}
//定义测试类
class ExampleA15{
          
   
    public static void main(String[] args) {
          
   
        //定义一个内部类 Cat实现 Animal接口
        class Cat implements Animal15 {
          
   
            public void shout(){
          
   
                System.out.println("喵喵……");
            }
        }
        animalShout(new Cat());//调用 animalShout()方法并且传入 Cat对象
    }
    //定义静态方法 animalShout()
    public static void animalShout(Animal15 an){
          
   
        an.shout();//调用传入对象 an的 shout()方法
    }
}

格式:

new 父类(参数列表)或 父类接口(){
          
   
	//匿名内部类实现部分
}

案例2:

//匿名内部类
interface Animal16 {
          
   
    void shout();
}
//定义测试类
class ExampleA16{
          
   
    public static void main(String[] args) {
          
   
        //定义匿名内部类作为参数传递给 animalShout()方法
        animalShout(new Animal16(){
          
   
            public void shout(){
          
   
                System.out.println("喵喵……");
            }
        });
    }
    //定义静态方法 animalShout()
    public static void animalShout(Animal16 an){
          
   
        an.shout();//调用传入对象 an的 shout()方法
    }
}

分步骤编写匿名内部类

①在调用 animalShout()方法时,在方法参数位置上写上 new Animal(){},这相当于创建了一个实例对象,并将对象作为参数传给 animalShout()方法。在 new Animal()后面有一对大括号,表示创建的对象为Animal的子类实例,该子类是匿名的。

animalShout(new Animal(){
          
   });

②在大括号中编写匿名子类的实现代码

animalShout(new Animal(){
          
   
    public void shout(){
          
   
        System.out.println("喵喵……");
    }
});

加深对接口类的认识

案例3:

//定义 PCI接口
interface PCI {
          
   
    void start();
    void stop();
}
//定义 NetWorkCard类实现 PCI接口
class NetWorkCard implements PCI {
          
   

    @Override
    public void start() {
          
   
        System.out.println("Send...");
    }

    @Override
    public void stop() {
          
   
        System.out.println("NetWork Stop");
    }
}
//定义 SoundCard类实现 PCI接口
class SoundCard implements PCI {
          
   

    @Override
    public void start() {
          
   
        System.out.println("Du do...");
    }

    @Override
    public void stop() {
          
   
        System.out.println("Sound Stop");
    }
}
//定义 MainBoard(主板)类
class MainBoard {
          
   
    //定义一个 userPCICard方法,接收 PCI类型的参数
    public void userPCICard(PCI pci) {
          
   
        pci.start();    //调用传入对象的方法
        pci.stop();
    }
}
//定义 Assembler(汇编程序)类
class Assembler {
          
   
    public static void main(String[] args) {
          
   
        MainBoard mb = new MainBoard(); //创建实例对象
        NetWorkCard nc = new NetWorkCard();
        mb.userPCICard(nc);
        //调用 MainBoard对象的 userPCICard()方法,将nc作为参数传入
        SoundCard sc = new SoundCard();
        mb.userPCICard(sc);
    }
}
经验分享 程序员 微信小程序 职场和发展