java用接口组装电脑_java 接口
时间: 2023-08-12 22:03:58 浏览: 53
Java中的接口是一个抽象类型,它定义了一组方法的签名,但没有具体的实现。可以使用接口来组装电脑中的各种组件,例如:
```java
// 定义CPU接口
public interface CPU {
public void calculate();
}
// 定义内存接口
public interface Memory {
public void store();
}
// 定义硬盘接口
public interface HardDisk {
public void read();
}
// 组装电脑
public class Computer {
private CPU cpu;
private Memory memory;
private HardDisk hardDisk;
public Computer(CPU cpu, Memory memory, HardDisk hardDisk) {
this.cpu = cpu;
this.memory = memory;
this.hardDisk = hardDisk;
}
public void work() {
cpu.calculate();
memory.store();
hardDisk.read();
}
}
// 实现Intel CPU
public class IntelCPU implements CPU {
public void calculate() {
System.out.println("Intel CPU is calculating.");
}
}
// 实现Kingston Memory
public class KingstonMemory implements Memory {
public void store() {
System.out.println("Kingston Memory is storing.");
}
}
// 实现WesternDigital HardDisk
public class WesternDigitalHardDisk implements HardDisk {
public void read() {
System.out.println("WesternDigital HardDisk is reading.");
}
}
// 测试
public class Test {
public static void main(String[] args) {
CPU cpu = new IntelCPU();
Memory memory = new KingstonMemory();
HardDisk hardDisk = new WesternDigitalHardDisk();
Computer computer = new Computer(cpu, memory, hardDisk);
computer.work();
}
}
```
在上面的例子中,可以看到Java中接口的作用,利用接口可以定义出CPU、内存、硬盘等组件的行为,然后通过组装可以构成一个完整的电脑。