码迷,mamicode.com
首页 > 编程语言 > 详细

java多态实例

时间:2018-02-08 20:15:25      阅读:228      评论:0      收藏:0      [点我收藏+]

标签:color   方法   类重写   and   java多态   post   out   school   hello   

学校有两个打印机,一个彩印,一个黑白印,都打印输出

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

 

java多态实例

标签:color   方法   类重写   and   java多态   post   out   school   hello   

原文地址:https://www.cnblogs.com/liubing2018/p/8432456.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!