学校有两个打印机,一个彩印,一个黑白印,都打印输出
public class printerDemo { public static void main(String[] args) { colorPrinter cp = new colorPrinter("惠普"); blackPrinter bp = new blackPrinter("联想"); school sch = new school(); sch.setColorPrinter(cp); sch.setBlacPkrinter(bp); cp.print("hello"); bp.print("hello"); } } class printer{ private String brand; public String getBrand() { return brand; } public printer(String brand){ this.brand = brand; } public void print(String content) {//需要重写 System.out.println(brand); } } class school{ private colorPrinter cp = null; private blackPrinter bp = null; public void setColorPrinter(colorPrinter cp) {//安装彩色打印机 this.cp = cp; } public void setBlacPkrinter(blackPrinter bp) {//安装黑白打印机 this.bp = bp; } public void print(String content) { cp.print(content); bp.print(content); } } class colorPrinter extends printer{ public colorPrinter(String brand){ super(brand); } public void print(String content) {//子类重写父类方法 System.out.println(getBrand()+"彩色打印:"+content); } } class blackPrinter extends printer{ public blackPrinter(String brand){ super(brand); } public void print(String content) {//子类重写父类方法 System.out.println(getBrand()+"黑白打印:"+content); } }