打印机有黑白的,有彩色的,学校都有打印机,用于打印,现在用多态来描述

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,"软件技术二班");

在这里插入图片描述

你可能感兴趣的:(Java2020上)