编写一个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
悬赏问题
- ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
- ¥15 网络设备配置与管理这个该怎么弄
- ¥20 机器学习能否像多层线性模型一样处理嵌套数据
- ¥20 西门子S7-Graph,S7-300,梯形图
- ¥50 用易语言http 访问不了网页
- ¥50 safari浏览器fetch提交数据后数据丢失问题
- ¥15 matlab不知道怎么改,求解答!!
- ¥15 永磁直线电机的电流环pi调不出来
- ¥15 用stata实现聚类的代码
- ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?