5.卡车要装载一批货物,货物有三种商品:电视、计算机和洗衣机。需要计算出大货车承载的3种货物的重量。要求有一个ComputeWeight接口,该接口中有一个抽象方法: public double computeWeight(); 设计3个实现接口的类:Television, Computer, WashMachine。这三个类通过实现接口给出自重。 定义一个Car类,该类用ComputeWeight接口类型的数组作为成员,那么该数组的单元可以存放Television, Computer, WashMachine对象的引用。 要求:设计程序能输出Car对象所装载的货物的总重量。
时间: 2024-03-21 15:42:20 浏览: 104
行业资料-交通装置-一种H3卡车用翻转面罩.zip
好的,以下是一个Java代码实现:
```java
public interface ComputeWeight {
double computeWeight();
}
public class Television implements ComputeWeight {
private double weight;
public Television(double weight) {
this.weight = weight;
}
@Override
public double computeWeight() {
return weight;
}
}
public class Computer implements ComputeWeight {
private double weight;
public Computer(double weight) {
this.weight = weight;
}
@Override
public double computeWeight() {
return weight;
}
}
public class WashMachine implements ComputeWeight {
private double weight;
public WashMachine(double weight) {
this.weight = weight;
}
@Override
public double computeWeight() {
return weight;
}
}
public class Car {
private ComputeWeight[] goods;
public Car(ComputeWeight[] goods) {
this.goods = goods;
}
public double getTotalWeight() {
double totalWeight = 0;
for (ComputeWeight good : goods) {
totalWeight += good.computeWeight();
}
return totalWeight;
}
}
public class Main {
public static void main(String[] args) {
ComputeWeight[] goods = new ComputeWeight[3];
goods[0] = new Television(50.0);
goods[1] = new Computer(30.0);
goods[2] = new WashMachine(100.0);
Car car = new Car(goods);
System.out.println("The total weight of the goods on the car is " + car.getTotalWeight() + "kg.");
}
}
```
在这个例子中,`ComputeWeight`接口定义了计算重量的抽象方法`computeWeight()`。`Television`、`Computer`和`WashMachine`类分别实现了该接口,并给出了自重。`Car`类中有一个`ComputeWeight`类型的数组作为成员变量,可以存放各种货物的对象引用。`Car`类中还有一个`getTotalWeight()`方法,用于计算总重量。在`Main`类中,创建了一个`Car`对象,并输出其装载的货物的总重量。
阅读全文