编写一个Java应用程序,货车要装载一批货物,货物由三种商品组成:电视、计算机和洗衣机。卡车需要计算出整批货物的重量。要求有一个ComputeWeight接口,该接口中有一个方法:public double computeWeight();有三个实现该接口的类:Television、Computer和WashMachine,分别重写computeWeight()方法给出自己的重量;有一个Truck类,该类用ComputeWeight接口类型的数组作为成员(Truck类面向接口),那么该数组的单元就可以存放Television对象的引用、Computer对象的引用或WashMachine对象的引用。程序能输出Truck对象所装载的货物的总重量。
3条回答 默认 最新
- iilmx 2021-11-02 12:55关注
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()); } }
如果对你有帮助的话,请采纳一下哈!
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 1无用 1