• java接口实例


    1.开发系统时,主体架构使用接口,接口构成系统的骨架
    2.这样就可以通过更换接口的实现类来更换系统的实现

    public class printerDemo{
    	public static void main(String[] args) {
    		ColorPrinter cp = new ColorPrinter("惠普");
    		BlackPrinter bp = new BlackPrinter("联想");
    		Teacher teacher = new Teacher("张三",26);
    		School school = new School();
    		
    		school.setPrinter(cp);
    		school.setPrinter(bp);
    		
    		school.print(school);
    		school.print(teacher);
    		
    		bp.print("abc");
    		cp.print("abc");
    	}
    }
    
    class School implements IInfo{
    	private Printer p = null;
    	public void setPrinter(Printer p) {
    		this.p = p;
    	}
    		
    	public void print(IInfo info) {
    		p.print(info.detail());
    	}
    	
    	public String detail() {
    		return "我是学校";
    	}
    }
    
    interface IInfo{//接口,教师和学校都有的方法
    	String detail();
    }
    
    abstract class Printer{
    	private String brand;
    	public String getBrand() {
    		return brand;
    	}
    	public Printer(String brand) {//构造方法
    		this.brand = brand;
    	}
    	
    	public abstract 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 Teacher implements IInfo{
    	private String name;
    	private int age;
    	
    	public Teacher(String name,int age) {
    		this.name = name;
    		this.age = age;
    	}
    	
    	public String detail() {
    	return "我的名字叫"+name+",年龄是"+age;
    	}
    }
    
  • 相关阅读:
    3个常用基于Linux系统命令行WEB网站浏览工具(w3m/Links/Lynx)
    Linux进程关系
    Linux信号基础
    Linux进程基础
    Linux架构
    Linux文本流
    Linux文件管理相关命令
    Linux命令行与命令
    【转载】 input 输入格式化
    【所见即所得】textarea 精确限制字数、行数,中、英、全半角混检 。源码带注释
  • 原文地址:https://www.cnblogs.com/liubing2018/p/8445437.html
Copyright © 2020-2023  润新知