Java中多态的使用

本文通过一个Java小程序示例,介绍了如何使用多态、继承等面向对象特性来设计一个灵活的打印系统。该系统允许根据不同的打印机类型(如彩色打印机和黑白打印机)进行打印操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这个小程序重点在于对School的设计,用到了重写,继承,多态等

public class PolyDemo{
    public static void main(String [] args){
        colorPrinter cp = new colorPrinter("lenovo");
        blackPrinter bp = new blackPrinter("epson");
        //bp.print();
        School s = new School();
        s.setPrinter(cp);
        s.centralPrint("hello java!");
    }
}
//拿父类的引用变量做参数
//耦合性太大,可扩展性小。对修改是封闭的,对扩展是开放的。父类的引用变量可以引用其子类的对象
//越是抽象越稳定

class School{
    private Printer p =null;
    /*private colorPrinter cp =null;
    private blackPrinter p =null;*/
    public void setPrinter(Printer p){
        this.p = p;
    }
    /*
    public void setPrinter(colorPrinter cp){
        this.cp = cp;
    }
     public void setPrinter(blackPrinter bp){
        this.bp = bp;
    }
    */
    public void centralPrint(String contend){
        p.print(contend);
    }
    /*
    public void centralPrint(String contend){
        cp.print(contend);
    }
    */
}
class Printer{
    private String brand;
    public Printer(String brand){
        this.brand = brand;
    }
    public String getBrand(){
        return brand;
    }
    public void print(String contend){
    }
}

class colorPrinter extends Printer{
    public colorPrinter(String brand){
        super(brand);
    }
    public void print(String contend){
        System.out.println(getBrand()+" the colorPrinter is printing of "+contend);
    }
}

class blackPrinter extends Printer{
    public blackPrinter(String brand){
        super(brand);
    }
    public void print(String contend){
        System.out.println(getBrand()+" the blackPrinter is printing of "+contend);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值