Java中多态的使用

来源:互联网 发布:google python style 编辑:程序博客网 时间:2024/05/17 08:00
这个小程序重点在于对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);    }}

0 0
原创粉丝点击