卡车要装载一批货物,货物有3种商品:电视、计算机和洗衣机。需要计算出大货车和小货车各自所装载的3中货物的总重量。编写一个Java应用程序,要求有一个ComputeWeight接口,该接口中有一个方法:public double computeWeight(); 有3个实现该接口的类:Television、Computer和WashMachine。这3个类通过实现接口ComputeWeight给出自重。有一个Car类,该类用ComputeWeight接口类型的数组作为成员,那么该数组的元素就可以存放Television对象的引用、Computer对象的引用或WashMachine对象的引用。程序能输出Car对象所装载的货物的总重量
package homework2; /* File name:Car.cpp Author:杨柳 Date:2017/11/6 IDE:eclipse */ class Car { ComputeWeight[] goods; double totalWeight=0; Car (ComputeWeight[] goods) { this.goods=goods; } public static void main(String[] args) { // TODO Auto-generated method stub ComputeWeight[] goods=new ComputeWeight[3]; goods[0]=new Television(345.6); //上转型对象 goods[1]=new Computer(789.3); goods[2]=new WashMachine(576.0); Car car=new Car(goods); double totalweight; totalweight=goods[0].computeWeight()+goods[1].computeWeight()+goods[2].computeWeight(); System.out.println("所装载的货物的总重量为:"+totalweight); } } interface ComputeWeight { public double computeWeight(); } public class Computer implements ComputeWeight { double cweight; Computer(double c){ this.cweight=c; } public double computeWeight(){ return cweight; } } public class Television implements ComputeWeight { //通过实现接口ComputerWeight给出自重 double tweight; Television(double t){ this.tweight=t; } public double computeWeight(){ return tweight; } } public class WashMachine implements ComputeWeight{ double wweight; WashMachine(double w){ this.wweight=w; } public double computeWeight(){ return wweight; } }