package com.hanqi.computer; public interface ICpu { public void yunSuan(); public String getPinpai(); }
package com.hanqi.computer; public class AMDCpu implements ICpu,IDisplay { @Override public void yunSuan() { System.out.println("我的运算速度也不错"); } @Override public String getPinpai() { return "AMD"; } @Override public void xianShi() { System.out.println("APU"); } }
package com.hanqi.computer; public class Computer { private ICpu cpu; private IDisplay display; public ICpu getCpu() { return cpu; } public void setCpu(ICpu cpu) { this.cpu = cpu; } public IDisplay getDisplay() { return display; } public void setDisplay(IDisplay display) { this.display = display; } public void run() { System.out.println("Cpu品牌 = " + cpu.getPinpai()); System.out.println(" 显卡品牌 = " + display.getPinpai()); cpu.yunSuan(); display.xianShi(); } }
package com.hanqi.computer; public interface IDisplay { public void xianShi(); // public 可不写 默认 public String getPinpai(); }
package com.hanqi.computer; public class IntelCpu implements ICpu { @Override public void yunSuan() { System.out.println("我的运算速度很快"); } @Override public String getPinpai() { return "Intel"; } }
package com.hanqi.computer; public class Ti960Display implements IDisplay { @Override public void xianShi() { System.out.println("显示图形"); } @Override public String getPinpai() { return "英伟达"; } }
package com.hanqi.computer; public class ZuZhuang { public static void main(String[] args) { //组装一台电脑 Computer c1 = new Computer(); ICpu intel = new IntelCpu(); c1.setCpu(intel); //有名对象 c1.setDisplay(new Ti960Display()); //匿名对象 c1.run(); Computer c2 = new Computer(); // AMDCpu a = new AMDCpu(); LongXin a = new LongXin2(); c2.setCpu(a); c2.setDisplay(a); c2.run(); } }
package com.hanqi.computer; public interface ICpuDisplay extends ICpu, IDisplay { }
package com.hanqi.computer; public abstract class LongXin implements ICpuDisplay { @Override public void yunSuan() { System.out.println("可以运算了"); } @Override public String getPinpai() { return "龙芯"; } @Override public abstract void xianShi(); //定义一个抽象方法 }
package com.hanqi.computer; public class LongXin2 extends LongXin { @Override public void xianShi() { System.out.println("可以显示"); } }