继承与多态

计算货物质量并分成三类:

interface ComputerWeight {                      //定义一个接口ComputerWeight
    public double computeWeight();
}
class Television implements ComputerWeight {    //定义一个类Television实现了接口ComputerWeight
   public double computeWeight(){               //重写接口的computeWeight()方法
     return 3.5;
   }
}
class Computer implements ComputerWeight {     
   public double computeWeight(){
      return 2.67;
   }                                       //重写computeWeight()方法-假设Computer自重为2.67


class WashMachine implements ComputerWeight {  
   public double computeWeight(){
      return 13.8;
   }                                 //重写computeWeight()方法-假设Computer自重为13.8
   
}
class Truck {                                   //卡车类-用接口型的数组goods作为数据成员
   ComputerWeight [] goods;                     //申明了一个接口型的数组goods(货物)
   double totalWeights=0;
   Truck(ComputerWeight[] goods) {              //构造函数--初始化其数据成员-数组goods
       this.goods=goods;
   }
   public double getTotalWeights() {
      totalWeights=0;
      for(int i=0;i<goods.length;i++)
      {
       totalWeights+=goods[i].computeWeight();
       }                                    //计算货物总重量
     
      return totalWeights;
   }   
}
public class CheckCarWeight {
   public static void main(String args[]) {
      ComputerWeight[] goods=new ComputerWeight[650];     //申明对象数组-650件货物
      for(int i=0;i<goods.length;i++) {                   //简单分成三类
           if(i%3==0)
             goods[i]=new Television();                   //把Television对象-赋值给接口变量
           else if(i%3==1)                                //goods数组元素--接口回调
             goods[i]=new Computer();
           else if(i%3==2)
             goods[i]=new WashMachine();
     }
     Truck truck=new Truck(goods);
     System.out.printf("\n货车装载的货物重量:%-8.5f kg\n",truck.getTotalWeights());
   }
}

posted @ 2017-11-13 23:06  宋建楠  阅读(524)  评论(0)    收藏  举报