接口与实现:实验2

接口:

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());
	}

}



  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值