接口回调(向上转型)

货车要装载一批货物,货物由三种商品组成:电视机、计算机和洗衣机。卡车需要计算出整批货物的重量。要求有一个ComputeWeight接口,该接口中有一法:    pubLic double computeWeight( );有三个实现该接口的类:TelevisionComputerWashMachine。这三个类通过实现接口computeTotalSales给出自重。有一个Truck类ComputeWeight接口类型的数组作为成员(Truck类面向接口),那么该数组的元素就可以存放Television对象的引用、Computer对象的引用或WashMachine对象的引用。程序能输出Tuck对象所装载的货物的总重量。

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

}  
class WashMachine implements ComputerWeight {   
                                  //重写computeWeight()方法-假设Computer自重为13.8
   public double computeWeight(){               
     return 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=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("
货车装载的货物重量:%-8.5f kg
",truck.getTotalWeights());
   }
}

 

原文地址:https://www.cnblogs.com/ljs-666/p/8013083.html