java介面例項

biubiubiuo發表於2018-02-12

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

 

相關文章