zoukankan      html  css  js  c++  java
  • 接口与实现:实验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());
    	}
    
    }



  • 相关阅读:
    C语言文法
    实验一
    词法分析
    py中文词频统计
    py字符串练习
    py画了个国旗
    熟悉常用的Linux操作
    大数据概述
    实验三、 递归下降分析程序实验
    简易c语言LL(1)文法
  • 原文地址:https://www.cnblogs.com/WALLACE-S-BOOK/p/9732332.html
Copyright © 2011-2022 走看看