2014年4月17日 星期四

Generics : 擴充泛型類別、實作泛型介面


class GenericNumber5 < T1,T2 >{
 private T1 number1;
 private T2 number2;
 
 public void setNumber1 (T1 number){
  this.number1 = number;
 }
 
 public T1 getNumber1 (){
  return number1;
 }
 
 public void setNumber2 (T2 number){
  this.number2 = number;
 }
 
 public T2 getNumber2 (){
  return number2;
 }
}

class SubGenericNumber5 < T1, T2, T3 > extends GenericNumber5 < T1, T2 > {
 private T3 number3;
 
 public void setNumber3 (T3 number){
  this.number3 = number;
 }
 
 public T3 getNumber3 (){
  return number3;
 }

}

public class GenericsCustomized {
 
 public static void main(String[] args) {
  SubGenericNumber5 < Integer, Long,Double> num = new SubGenericNumber5 <Integer, Long,Double&gr;();
  num.setNumber1(10);
  num.setNumber2( 200L );
  num.setNumber3(300.5);
  Double d = num.getNumber1() + num.getNumber2() + num.getNumber3();
  System.out.println("Total : "+d);
 
 }

}


執行結果
若要使用父類別時,父類別上宣告的型態持有者數目在繼承下來時,必須全寫。例如:SubGenericNumber 定義為 class SubGenericNumber5 extends GenericNumber5 ,則會發生編譯錯誤
Exception in thread "main" java.lang.Error: Unresolved compilation problems: 
 Incorrect number of arguments for type SubGenericNumber5; it cannot be parameterized with arguments 
 Incorrect number of arguments for type SubGenericNumber5; it cannot be parameterized with arguments 

 at GenericsCustomized.main(GenericsCustomized.java:38)
但,若子類別不用到父類別定義的資料、方法時,則可改寫如下。不過,建議將父親類別的型態持有者都保留。
class GenericNumber5 <T1,T2>{
 private T1 number1;
 private T2 number2;
 
 public void setNumber1 (T1 number){
  this.number1 = number;
 }
 
 public T1 getNumber1 (){
  return number1;
 }
 
 public void setNumber2 (T2 number){
  this.number2 = number;
 }
 
 public T2 getNumber2 (){
  return number2;
 }
}

class SubGenericNumber5 <T3> extends GenericNumber5 {
 private T3 number3;
 
 public void setNumber3 (T3 number){
  this.number3 = number;
 }
 
 public T3 getNumber3 (){
  return number3;
 }

}

public class GenericsCustomized {
 
 public static void main(String[] args) {

  SubGenericNumber5 <Double> num = new SubGenericNumber5 <Double>();
  num.setNumber3(300.5);
  Double d = num.getNumber3();
  System.out.println("Total : "+d);
  
 
 }

}
執行結果

沒有留言:

張貼留言