1创建接口
package lianxi; public interface ICpu { public boolean neiCun();//内存接口 }
2创建一个类 连接这个接口
package lianxi; public class cpuceshi implements ICpu { @Override public boolean neiCun() { System.out.println("CPU内存太小了"); return true; } }
3创建一个父类
public class computer { private ICpu cpu; public ICpu getDiannao() { return cpu; } public void setDiannao(ICpu cpu) { this.cpu = cpu; } double rongliang; boolean CP(){ boolean rtn=true; if (rongliang>50){ System.out.println("安装了一个"+rongliang+"兆的CPU"); rtn=false; }else if(cpu==null){ System.out.println("未安装CPU"); rtn=false; }else{ rtn=this.cpu.neiCun(); }return true; } }
4创建子类调用
package lianxi; public class CeShi { public static void main(String[] args) { // TODO 自动生成的方法存根 computer cop=new computer(); cop.rongliang=34;
System.out.println("当容量为"+cop.rongliang+"的时候"); cop.setDiannao(new cpuceshi()); cop.CP(); } }
package lianxi; public class CeShi { public static void main(String[] args) { // TODO 自动生成的方法存根 computer cop=new computer(); cop.rongliang=70; System.out.println("当容量为"+cop.rongliang+"的时候"); cop.setDiannao(new cpuceshi()); cop.CP(); } }
CPU接口练习 (仅以此程序证明 某个同学真的有毒!有毒!!!)
原文:http://www.cnblogs.com/zhanghaozhe8462/p/5149637.html