接口:
package mypackage;
public interface ComputeWeight {
public abstract double computeweight();
}
接口实现:
package mypackage;
public class Computer implements ComputeWeight {
@Override
public double computeweight() {
// TODO 自动生成的方法存根
return 3.0;
}
}
package mypackage;
public class Television implements ComputeWeight {
@Override
public double computeweight() {
// TODO 自动生成的方法存根
return 3.5;
}
}
package mypackage;
public class WashMachine implements ComputeWeight {
@Override
public double computeweight() {
// TODO 自动生成的方法存根
return 10.5;
}
}
类:
package mypackage;
public class Truck {
ComputeWeight []goods;
public Truck(ComputeWeight []goods){
this.goods=goods;
}
public void setGoods(ComputeWeight []goods ){
this.goods=goods;
}
public double getTotalWeight() {
double totalWeights=0;
for(int i=0; i<goods.length; i++) {
totalWeights += goods[i].computeweight();
}
return totalWeights;
}
}
主类:
package Main;
import mypackage.*;
public class CheckCarWeight {
public static void main(String[] args) {
// TODO 自动生成的方法存根
ComputeWeight [] goods =new ComputeWeight[650];
for(int i=0; i<goods.length; i++) {
if(i%3==0) goods[i]=new Television();
else if(i%3==1) goods[i]=new Computer();
else goods[i]=new WashMachine();
}
Truck truck=new Truck(goods);
System.out.println("货物重量:"+
truck.getTotalWeight());
goods=new ComputeWeight[68];
for(int i=0; i<goods.length; i++) {
if(i%2==0) goods[i]=new Television();
else goods[i]= new WashMachine();
}
truck.setGoods(goods);
System.out.println("货物重量:"+
truck.getTotalWeight());
}
}