• java多态-优化上个实例


    开闭原则:对修改是封闭的,对扩展是开放的,不要违反开闭原则。

    可以使用多态解决这个问题。父类的引用变量可以引用子类是对象。

    写的越是抽象,越是稳定

    public class printerDemo {
    	public static void main(String[] args) {
    		/*colorPrinter cp = new colorPrinter("惠普");
    		blackPrinter bp = new blackPrinter("联想");*/
    		printer p1 = new colorPrinter("惠普");
    		printer p2 = new blackPrinter("联想");
    		printer p3 = new DDDPrinter("索尼");
    		school sch = new school();
    		/*sch.setBlackPrinter(bp);
    		sch.setColorPrinter(cp);*/
    		sch.setPriner(p1);
    		sch.setPriner(p2);
    		/*cp.print("abc");
    		bp.print("abc");*/
    		p1.print("hello");
    		p2.print("hello");
    		p3.print("hello");
    	}
    	
    }
    
    class school{
    	/*private colorPrinter cp = null;
    	private blackPrinter bp = null;*/
    	private printer p = null;
    	/*public void setColorPrinter(colorPrinter cp) {
    		this.cp = cp;
    	}
    	public void setBlackPrinter(blackPrinter bp) {
    		this.bp = bp;
    	}*/
    	public void setPriner(printer p) {
    		this.p = p;
    	}
    	public void print(String content) {
    		/*cp.print(content);
    		bp.print(content);*/
    		p.print(content);
    	}
    }
    
    class printer{
    	private String brand;
    	public String getBrand() {
    		return brand;
    	}
    	
    	public printer(String brand) {
    		this.brand = brand;
    	}
    	
    	public void print(String 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);
    	}
    }
    
    class DDDPrinter extends printer{
    	public DDDPrinter(String brand) {
    		super(brand);
    	}
    	
    	public void print(String content) {
    		System.out.println(getBrand()+"3D打印:"+content);
    	}
    }
    
  • 相关阅读:
    mysql 中只能使用 localhost 登录,用ip不能登陆
    在springboot 和 mybatis 项目中想要显示sql 语句进行调试
    从一张表数据导入到另一张表
    mysql 中 delete 子查询的限制
    配置eureka 老是报错connected time out 或者 refused connected
    Linux-TCP 出现 RST 的几种情况
    MySQL-优化之 index merge(索引合并)
    Python-Mac 安装 PyQt4
    PHP-PHP-FPM的max_children一些误区
    Linux-磁盘及网络IO工作方式解析
  • 原文地址:https://www.cnblogs.com/liubing2018/p/8439162.html
Copyright © 2020-2023  润新知