打印机有多种类型,如黑白打印机、彩色打印机等,编程实现计算机可以分别连接黑白打印机和黑白打印机和彩色打印机进行信息打印。系统要具有良好的可扩展性与维护性。

img


public abstract class Printer {
    String type;
    abstract void print(String s);
}
public class BlackPrinter extends Printer{

    public BlackPrinter() {
        super.type = "黑白打印机";
        System.out.println(super.type+"开始工作");
    }
    
    @Override
    void print(String s) {
        System.out.println("打印内容:"+s);
    }
}

public class ColorPrinter extends Printer{

    public ColorPrinter() {
        super.type = "彩色打印机";
        System.out.println(super.type+"开始工作");
    }
    
    @Override
    void print(String s) {
        System.out.println("打印内容:"+s);
    }
}

public class Computer {
    
    public void print(Printer p,String s) {
        p.print(s);
    }
}

public class Test {
    public static void main(String[] args) {
        Printer blackPrinter = new BlackPrinter();
        
        Printer colorPrinter = new ColorPrinter();
        
        Computer computer = new Computer();
        computer.print(blackPrinter, "我爱我的祖国!");
        computer.print(colorPrinter, "祝您健康长寿!");
        
    }
}

定义其他几个子类,继承Printer类,重写print()方法,输出要求的内容。

public class Printer{
  private String type;
  public void print(String s){
    System.out.println(s);
  }
}