货车要装载一批货物,货物由电视机、计算机和洗衣机3种商品组成。卡车需要计算出整批货物的质量,具体要求如下。 (1)要求有一个ComputerWeight接口,该接口中有一个方法: public double computerWeight() (2) 要求有3个实现该接口的类,即Television、Computer和WashMachine。 (3)要求有一个Truck类,该类以computerWeight接口类型的数组作为成员(Truck类面向接口),那么该数组的单元就可以放Television对象的引用、Computer对象的引用或WashMachine对象的引用。程序能输出Truck对象所装载的货物的总质量。 程序运行效果图如下:货车装载的货物质量: 4319. 69000kg 货车装载的货物质量: 588. 20000kg
时间: 2024-01-21 10:20:12 浏览: 144
货物装载问题
以下是实现该程序的Java代码:
ComputerWeight.java
```java
public interface ComputerWeight {
public double computerWeight();
}
```
Television.java
```java
public class Television implements ComputerWeight {
private double weight;
public Television(double weight) {
this.weight = weight;
}
@Override
public double computerWeight() {
return weight;
}
}
```
Computer.java
```java
public class Computer implements ComputerWeight {
private double weight;
public Computer(double weight) {
this.weight = weight;
}
@Override
public double computerWeight() {
return weight;
}
}
```
WashMachine.java
```java
public class WashMachine implements ComputerWeight {
private double weight;
public WashMachine(double weight) {
this.weight = weight;
}
@Override
public double computerWeight() {
return weight;
}
}
```
Truck.java
```java
public class Truck {
private ComputerWeight[] goods;
public Truck(ComputerWeight[] goods) {
this.goods = goods;
}
public double getTotalWeight() {
double totalWeight = 0;
for (ComputerWeight good : goods) {
totalWeight += good.computerWeight();
}
return totalWeight;
}
}
```
Main.java
```java
public class Main {
public static void main(String[] args) {
Television tv1 = new Television(1200);
Television tv2 = new Television(800);
Computer computer = new Computer(2000);
WashMachine wm1 = new WashMachine(1000);
WashMachine wm2 = new WashMachine(319);
ComputerWeight[] goods1 = {tv1, tv2, computer, wm1};
Truck truck1 = new Truck(goods1);
System.out.println("货车装载的货物质量: " + truck1.getTotalWeight() + "kg");
ComputerWeight[] goods2 = {wm2, computer};
Truck truck2 = new Truck(goods2);
System.out.println("货车装载的货物质量: " + truck2.getTotalWeight() + "kg");
}
}
```
输出结果:
```
货车装载的货物质量: 4319.0kg
货车装载的货物质量: 588.0kg
```
阅读全文