一、代码
/*
正常,不用多态写
class School{
public CaiSeDayin cy;
public HeBaiDayin hy;
public void anZhuang(CaiSeDayin cy){
this.cy = cy;
}
public void anZhuangh(HeBaiDayin hy){
this.hy = hy;
}
public void print(String contex){
cy.print(contex);
}
}
*/
//多态写法,这样添加打印机就添加一个Dayin的子类就可以了
class School{
public Dayin dayinji;
public void anZhuang(Dayin dayinji){
this.dayinji = dayinji;
}
public void print(String contex){
dayinji.print(contex);
}
}
class Dayin{
public String pinpai;
public void print(String contex){}
}
class CaiSeDayin extends Dayin{
public void print(String contex){
System.out.println("彩色打印机打印" + contex);
}
}
class HeBaiDayin extends Dayin{
public void print(String contex){
System.out.println("黑白打印机打印" + contex);
}
}
class ZhenDayin extends Dayin{
public void print(String contex){
System.out.println("针打印机打印" + contex);
}
}
public class Printor {
public static void main(String[] args) {
/*正常,不用多态写
School s = new School();
CaiSeDayin c = new CaiSeDayin();
s.anZhuang(c);
s.print("xiao");
HeBaiDayin h = new HeBaiDayin();
s.anZhuangh(h);
s.print("wei");
*/
School s = new School();
CaiSeDayin c = new CaiSeDayin();
s.anZhuang(c);
s.print("xiao");
HeBaiDayin h = new HeBaiDayin();
s.anZhuang(h);
s.print("wei");
ZhenDayin z = new ZhenDayin();
s.anZhuang(z);
s.print("小伟");
}
}
/*
彩色打印机打印xiao
黑白打印机打印wei
针打印机打印小伟
*/