计算重量
Problem Description
1.实验目的
(1) 熟悉接口的声明、创建、使用
(2) 能利用接口的思想解决一般问题
2.实验内容
有一个ComputerWeight接口,该接口有一个方法:
public double computeWeight()
有三个实现该接口的类Television、Computer、WashMachine,这三个类通过实现接口ComputerWeight,计算自身的重量,其中Television重量为45.5,Computer重量为65.5,WashMachine重量为145
有一个Car类,该类用ComputerWeight数组作为成员,ComputerWeight数组的单元可以存放Television、Computer、WashMachine对象的引用,程序能输出Car类对象的总重量。
3.实验要求
补充完整下面的代码
// 你的代码
public class Main
{
public static void main(String args[])
{ ComputerWeight[] goodsOne=new ComputerWeight[50],
goodsTwo=new ComputerWeight[22] ;
for(int i=0;i<goodsOne.length;i++)
{ if(i%3==0)
goodsOne[i]=new Television();
else if(i%3==1)
goodsOne[i]=new Computer();
else if(i%3==2)
goodsOne[i]=new WashMachine();
}
for(int i=0;i<goodsTwo.length;i++)
{ if(i%3==0)
goodsTwo[i]=new Television();
else if(i%3==1)
goodsTwo[i]=new Computer();
else if(i%3==2)
goodsTwo[i]=new WashMachine();
}
Car largeTruck=new Car(goodsOne);
System.out.println("The weight of the goods loaded in the large truck: "+largeTruck.getTotalWeights());
Car pickup=new Car(goodsTwo);
System.out.println("The weight of the goods loaded in the pickup: "+pickup.getTotalWeights());
}
}
Output Description
The weight of the goods loaded in the large truck: 4207.0
The weight of the goods loaded in the pickup: 1837.5
解题代码
// ComputerWeight 接口
interface ComputerWeight{
// 抽象方法computeWeight
double computeWeight();
}
// Television类实现了 ComputerWeight 接口
class Television implements ComputerWeight{
// 实现computeWeight方法
@Override
public double computeWeight() {
// 返回重量
return 45.5;
}
}
// Computer类实现了 ComputerWeight 接口
class Computer implements ComputerWeight{
// 实现computeWeight方法
@Override
public double computeWeight() {
// 返回重量
return 65.5;
}
}
// WashMachine类实现了 ComputerWeight 接口
class WashMachine implements ComputerWeight{
// 实现computeWeight方法
@Override
public double computeWeight() {
// 返回重量
return 145;
}
}
// Car类
class Car{
// 成员goods ComputerWeight类型数组
private ComputerWeight[] goods = null;
// 带参构造方法
public Car(ComputerWeight[] goods) {
this.goods = goods;
}
// 无参构造
public Car() {
}
// 获取总重量的方法
public double getTotalWeights(){
double total = 0.;
// 循环遍历goods 计算总重量
for (ComputerWeight computerWeight: goods){
total += computerWeight.computeWeight();
}
// 返回结果
return total;
}
}