1.定义接口
package com.lianxi; public interface ICpu { public String pinpai(String a);//品牌 public void yunxing();//运行情况 public int luosigeshu(int d);//螺丝的个数 }
2.定义计算机
package com.lianxi; public class JSJ { private ICpu cpu; //命名 public ICpu getCpu() { return cpu; } //getter and setter public void setCpu(ICpu cpu) { this.cpu = cpu; } private String neiCun; //定义属性 private String yingPan;//定义属性 public String getNeiCun() { return neiCun; } public void setNeiCun(String neiCun) { this.neiCun = neiCun; } public String getYingPan() { return yingPan; //getter and setter } public void setYingPan(String yingPan) { this.yingPan = yingPan; } void kaiJi() //定义方法 { intelcpu inte = new intelcpu(); inte.yunxing(); System.out.println("正在开机"); } void guanJi() //定义方法 { System.out.println("正在关机"); } int jiSuan(int a,int b) //定义方法 { return (a+b); } }
3. 定义CPU
package com.lianxi; public class intelcpu implements ICpu { @Override public String pinpai(String a) //实现品牌 { return a; } @Override public void yunxing() //实现运行 { System.out.println("CPU开始运行"); } @Override public int luosigeshu(int d) //实现螺丝个数 { // TODO 自动生成的方法存根 return d; } }
4.实例化并运行
package com.lianxi; public class TestJSJ { public static void main(String[] args) { JSJ jsj = new JSJ(); jsj.setYingPan("500G"); jsj.setNeiCun("极品内存条"); intelcpu cpu = new intelcpu(); int a =cpu.luosigeshu(5); String b = cpu.pinpai("Intel牌"); jsj.kaiJi(); int c = jsj.jiSuan(5, 6); System.out.println("计算机硬盘 = "+jsj.getYingPan()); System.out.println("计算机内存是"+jsj.getNeiCun()); System.out.println("cup上一共有 "+ a +"个螺丝"); System.out.println("cpu的品牌是 "+ b); System.out.println("计算5 + 6 的结果是 " + c); jsj.guanJi(); /* 运行结果如下: CPU开始运行 正在开机 计算机硬盘 = 500G 计算机内存是极品内存条 cup上一共有 5个螺丝 cpu的品牌是 Intel牌 计算5 + 6 的结果是 11 正在关机 */ } }