【多态】面向接口的编程思想

开发系统时,主体架构使用接口,接口构成系统的骨架 。这样就可以通过更换接口的实现类来更换系统的实现。

实例:学校要安装彩色和黑白两台打印机,分别打印教员和机构的相关信息(用接口实现)

教员和机构的相关信息都需要打印,这种like-a关系,使用接口把二者共有的特性抽象出来,在这里就是把要打印的信息抽象成接口:
detail()方法是一个抽象方法,默认可以不写abstract关键字

interface IInfo{
    String detail();
}

教员类初始化教员信息,再实现IInfo方法

class Teacher implements IInfo{
    private String name;
    private int age;
    public Teacher(String name,int age){
        this.name=name;
        this.age=age;
    }
    //实现接口IInfo的具体方法
    public String detail(){
        return "Hello, I'm "+name+", "+age+" years old.";
    }

}

学校类安装打印机,打印数据,实现IInfo方法

class School implements IInfo{
    private Printer p=null//安装打印机
    //拿父类的引用变量作为参数,好处就是可以接收任何子类的对象
    //越是抽象的事物越稳定
    public void setPrinter(Printer p){
        this.p=p;
    }
    //接口的引用变量可以引用它实现类的对象
    //多态,程序设计的时候主体框架使用接口或抽象类,是程序又很好的扩展性
    public void print(IInfo info){
        p.Print(info.detail());
    }
    //实现接口IInfo的具体方法
    public String detail(){
        return "Welcome to xxx School";
    }
}

各式打印机继承了打印机类,所以打印机类的打印方法由具体的子类实现,这里的Print方法应该是一个抽象方法,打印机类是一个抽象类。

abstract class Printer{
    private String brand;
    public Printer(String brand){
        this.brand=brand;
    }
    public String getBrand(){
        return brand;
    }
    public abstract print(String content);
}

打印机子类实现具体的打印方法:

//彩色打印机
class ColorPrinter extends Printer{
    public ColorPrinter(String brand){
        super(brand);
    }
    public void print(String content){
        System.out.println(getBrand()+"ColorPrinter:"+content)
    }
}

class BlackPrinter extends Printer{
    public BlackPrinter(String brand){
        super(brand);
    }
    public void print(String content){
        System.out.println(getBrand+"BlackPrinter:"+content);
    }
}

主方法new对象:打印机对象,学校对象,教员对象

public class printerDemo{
    public static void main(String []args){
        colorPrinter cp=new colorPrinter("HP");//define printer "HP" is colorPrinter
        BWPrinter bp=new BWPrinter("Sony");//define printer "Sony" is BWPrinter
        School school=new School(); //init a school
        Teacher t=new Teacher("Lily",30);
        //school.setColorPrinter(cp); //The school installs colorPrinter "HP"
        //school.Print("Hello Java"); //The school print content with colorPrinter
        //school.setBWPrinter(bp);//The school installs BWPrinter "Sony"
        //school.Print("Hello Java"); //The school print content with BWPrinter
        school.setPrinter(cp);//set BWPrinter
        school.print(t);//print teacher info
        school.setPrinter(bp);//set colorPrinter
        school.print(school);//print school info
    }
}

输出结果
这里写图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值