首先是要有一个ComputeWeight的接口,里面包括computeWeight方法;
构造Television、Computer和WashMachine三个类,分别实现ComputeWeight接口,每个类应包含自身重量的属性,computeWeight方法可设置为返回该重量属性;如:
class Television implements Compute
Weight{
private double weight;
.......
//override
public double computeWeight(){
return this.weight;
}
....
}
构造一个Car类,用ComputeWeight接口类型的数组作为成员,如
ComputeWeight[] weights = new ComputeWeight[3];
该数组的单元就可以存放Television对象的引用、Computer对象的引用或WashMachine对象的引用.如
weights[0] = new Television();
然后可以根据weights数组计算机总重量,如:
total = weights[0].computeWeight() + weights[1]......;
不知是否清楚一点点了?