计算机的主要组成部分有:
CPU
硬盘
内存
看到这里我们首先想到的是has a 的关系,所以我们需要定义一个CPU的接口,硬盘接口以及内存接口
CPU接口
public interface CPU {
public String getBrand();//品牌
}
硬盘接口
public interface HardDisk {
public String getType();//硬盘类型
}
内存接口
public interface EMS {
public String getCapacity();//容量
}
当然我们也需要给这些接口定义各自的子类
//CUP子类Inter类
public class Inter implements CPU {
public String getBrand() {
return "Inter";
}
//CUP子类ADM类
public class ADM implements CPU {
public String getBrand() {
return "ADM";
}
//硬盘子类机械硬盘及内存
public class MHD implements HardDisk {
public String getType() {
return "机械2000GB";
}
//硬盘子类固态硬盘及内存
public class SSD implements HardDisk {
public String getType() {
return "固态3000GB";
}
//内存子类2GB内存
public class Two implements EMS {
public String getCapacity() {
return "2GB";
}
//内存子类4GB内存
public class Four implements EMS {
public String getCapacity() {
return "4GB";
}
//内存子类8GB内存
public class Eight implements EMS {
public String getCapacity() {
return "8GB";
}
我们需要一个电脑类来接收CPU、EMS和HardDisk以及输出的方法
CPU cpu;
EMS ems;
HardDisk hardDisk;
this.cpu = cpu;
}
this.ems = ems;
}
this.hardDisk = hardDisk;
}
System.out.println("计算机的信息如下:");
System.out.println("CPU的品牌是:"+cpu.getBrand()+",主频是:3.8GHZ");
System.out.println("硬盘容量是:"+ems.getCapacity());
System.out.println("内存容量是:"+hardDisk.getType());
}
public static void main(String[] args) {
Computer computer = new Computer();
CPU cpu = new Inter();
EMS ems = new Eight();
HardDisk hardDisk = new SSD();
computer.setCPU(cpu);
computer.setHardDisk(hardDisk);
computer.setEMS(ems);
computer.show();
}