Java.编写一个应用程序,用类描述计算机中CPU的速度和硬盘的 容量,要求含有四个类:PC、CPU、HardDisk和Test。(
时间: 2024-10-27 20:10:41 浏览: 29
在Java中,你可以创建如下的四个类来描述计算机的CPU速度和硬盘容量:
```java
// Computer类作为基类,包含通用属性
class PC {
private String model;
protected double cpuSpeed; // CPU速度(单位通常为GHz)
private long hardDiskCapacity; // 硬盘容量(单位通常为GB)
public PC(String model) {
this.model = model;
}
// 提供getter和setter方法
public String getModel() { return model; }
public void setModel(String model) { this.model = model; }
public double getCpuSpeed() { return cpuSpeed; }
public void setCpuSpeed(double cpuSpeed) { this.cpuSpeed = cpuSpeed; }
public long getHardDiskCapacity() { return hardDiskCapacity; }
public void setHardDiskCapacity(long hardDiskCapacity) { this.hardDiskCapacity = hardDiskCapacity; }
}
// CPU类是PC类的一个特化,表示具体的CPU类型
class CPU extends PC {
public CPU(String model, double speed) {
super(model);
this.cpuSpeed = speed;
}
}
// HardDisk类也继承自PC,表示硬盘的具体类型
class HardDisk extends PC {
public HardDisk(String model, long capacity) {
super(model);
this.hardDiskCapacity = capacity;
}
}
// Test类用于测试和演示如何使用这四个类
public class Test {
public static void main(String[] args) {
// 创建并初始化CPU和HardDisk实例
CPU intelCorei5 = new CPU("Intel Core i5", 3.5);
HardDisk samsungSSD = new HardDisk("Samsung SSD", 500);
// 调用方法展示属性
System.out.println("CPU: " + intelCorei5.getModel() + ", Speed: " + intelCorei5.getCpuSpeed() + " GHz");
System.out.println("Hard Disk: " + samsungSSD.getModel() + ", Capacity: " + samsungSSD.getHardDiskCapacity() + " GB");
// 将它们视为PC类型进行操作(体现多态)
PC computer = intelCorei5;
computer.setCpuSpeed(4.0); // 通过对象引用可以修改其CPU速度
computer.setHardDiskCapacity(750); // 修改硬盘容量
System.out.println("Updated Computer: " + computer.getModel() + ", New Speed: " + computer.getCpuSpeed() + " GHz, New Capacity: " + computer.getHardDiskCapacity() + " GB");
}
}
```
阅读全文