编写一个Java应用程序,货车要装载一批货物,货物由三种商品组成:电视、计算机和洗衣机。卡车需要计算出整批货物的重量。要求有一个ComputeWeight接口,该接口中有一个方法:public double computeWeight();有三个实现该接口的类:Television、Computer和WashMachine,分别重写computeWeight()方法给出自己的重量;有一个Truck类,该类用ComputeWeight接口类型的数组作为成员(Truck类面向接口),那么该数组的单元就可以存放Television对象的引用、Computer对象的引用或WashMachine对象的引用。程序能输出Truck对象所装载的货物的总重量。
public interface ComputeWeight {
double computeWeight();
}
public class Television implements ComputeWeight {
@Override
public double computeWeight() {
return 10;
}
}
public class Computer implements ComputeWeight{
@Override
public double computeWeight() {
return 20.5;
}
}
public class WashMachine implements ComputeWeight{
@Override
public double computeWeight() {
return 50.5;
}
}
public class Truck {
public ComputeWeight[] array = new ComputeWeight[3];
public double cal(){
double sum = 0;
for (int i = 0; i < this.array.length; i++){
sum += this.array[i].computeWeight();
}
return sum;
}
}
public class TestMain {
public static void main(String[] args) {
Television television = new Television();
Computer computer = new Computer();
WashMachine washMachine = new WashMachine();
Truck truck = new Truck();
truck.array[0] = television;
truck.array[1] = computer;
truck.array[2] = washMachine;
System.out.println("Truck对象所装载的货物的总重量: " + truck.cal());
}
}
如果对你有帮助的话,请采纳一下哈!
public static void main(String[] args) {
Truck truck = new Truck();
ComputeWeight television = new Television();
ComputeWeight computer = new Computer();
ComputeWeight washMachine1 = new WashMachine();
ComputeWeight washMachine2 = new WashMachine();
ComputeWeight washMachine3 = new WashMachine();
ComputeWeight[] weights = new ComputeWeight[]{television, computer, washMachine1, washMachine2, washMachine3};
truck.setWeights(weights);
System.out.println("卡车内总重量为:" + truck.getWeights());
}
interface ComputeWeight {
public double computeWeight();
}
static class Truck {
ComputeWeight[] weights;
public int getWeights() {
int sum = 0;
if (weights == null) {
return sum;
}
for (ComputeWeight weight : weights) {
sum += weight.computeWeight();
}
return sum;
}
public void setWeights(ComputeWeight[] weights) {
this.weights = weights;
}
}
static class Television implements ComputeWeight {
@Override
public double computeWeight() {
return 1;
}
}
static class Computer implements ComputeWeight {
@Override
public double computeWeight() {
return 2;
}
}
static class WashMachine implements ComputeWeight {
@Override
public double computeWeight() {
return 3;
}
}
家庭作业要自己动手。