java多型例項

biubiubiuo發表於2018-02-08

學校有兩個印表機,一個彩印,一個黑白印,都列印輸出

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);
	}
}

 

相關文章