package jiCheng_duoTai;
//public class DaYinJi {
// public static void main(String[] args) {
// School s = new School();
// BlackPrinter bp = new BlackPrinter("惠普牌");
// ColorPrinter cp = new ColorPrinter("三星牌");
// s.usePrinter(bp,"武漢大學");//打印的內容
// s.usePrinter(cp,"軟件技術二班");//打印的內容
// }
//}
class Printer{//父類,打印機
private String brand;
public Printer() {}
public Printer(String brand) {
this.brand = brand;
}
public void print(String content) {
System.out.println(content);
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
}
class BlackPrinter extends Printer {//子類,黑白打印機
public BlackPrinter() {
super();
}
public BlackPrinter(String brand) {
super(brand);
}
public void print (String content) {
System.out.println(getBrand()+"黑白打印機:"+content);
}
}
class ColorPrinter extends Printer{//子類,彩色打印機
public ColorPrinter() {
super();
}
public ColorPrinter(String brand) {
super(brand);
}
public void print (String content) {
System.out.println(getBrand()+"彩色打印機:"+content);
}
}
//class School{
// public void usePrinter(BlackPrinter bp,String content) {
// bp.print(content);
// }
// public void usePrinter(ColorPrinter cp,String content) {
// cp.print(content);
// }
//}
//首先,上面的代碼未使用到多態的形式,如果打印機的品牌很多,上面的代碼就不適用了,所以進行改進,改爲多態形式
//首先將上面的School類進行註釋,進行新的編寫
class School{
public void usePrinter(Printer p,String content) {
p.print(content);
}
}
//其次,將main函數代碼塊進行註釋,進行重新的編寫,進而實現多態
public class DaYinJi {
public static void main(String[] args) {
School s = new School();
Printer p1=new BlackPrinter("惠普牌");
Printer p2=new ColorPrinter("三星牌");
s.usePrinter(p1,"武漢大學");
s.usePrinter(p2,"軟件技術專業");
}
}
//對於上面的代碼也可以改用下面的這個形式
//School s = new School();
//BlackPrinter bp = new BlackPrinter("惠普牌");
//ColorPrinter cp = new ColorPrinter("三星牌");
//s.usePrinter(bp,"武漢大學");//父類引用指向子類對象 p=bp;
//s.usePrinter(cp,"軟件技術二班");
打印機有黑白的,有彩色的,學校都有打印機,用於打印,現在用多態來描述
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.