用java运行卡车要装载一批货物,货物有三种商品:电视、计算机和洗衣机。需要计算出大货车承载的3种货物的重量。要求有一个ComputeWeight接口,该接口中有一个抽象方法: public double computeWeight(); 设计3个实现接口的类:Television, Computer, WashMachine。这三个类通过实现接口给出自重。 定义一个Car类,该类用ComputeWeight接口类型的数组作为成员,那么该数组的单元可以存放Television, Computer, WashMachine对象的引用。 要求:设计程序能输出Car对象所装载的货物的总重量。
时间: 2024-03-14 12:43:50 浏览: 125
JAVA类加载
5星 · 资源好评率100%
以下是代码实现:
```java
// ComputeWeight接口
interface ComputeWeight {
double computeWeight();
}
// Television类
class Television implements ComputeWeight {
private double weight = 50;
public double computeWeight() {
return weight;
}
}
// Computer类
class Computer implements ComputeWeight {
private double weight = 20;
public double computeWeight() {
return weight;
}
}
// WashMachine类
class WashMachine implements ComputeWeight {
private double weight = 70;
public double computeWeight() {
return weight;
}
}
// Car类
class Car {
private ComputeWeight[] goods;
public Car(ComputeWeight[] goods) {
this.goods = goods;
}
public double getTotalWeight() {
double total = 0;
for (ComputeWeight g : goods) {
total += g.computeWeight();
}
return total;
}
}
// 测试程序
public class Test {
public static void main(String[] args) {
ComputeWeight[] goods = new ComputeWeight[3];
goods[0] = new Television();
goods[1] = new Computer();
goods[2] = new WashMachine();
Car car = new Car(goods);
System.out.println("Car对象所装载的货物的总重量为:" + car.getTotalWeight() + "kg");
}
}
```
运行程序后,会输出:Car对象所装载的货物的总重量为:140.0kg。
阅读全文