接口回調(向上轉型)


貨車要裝載一批貨物,貨物由三種商品組成:電視機、計算機和洗衣機。卡車需要計算出整批貨物的重量。要求有一個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("\n貨車裝載的貨物重量:%-8.5f kg\n",truck.getTotalWeights());
   }
}

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM