大家好
下面這個泛型的例子,為何
Car<Number,String,Integer> car1 = new Car<Number,String,Integer>(1,2L); 這行
compile會過呢?建構子有明確定義兩個參數要同類別,但我傳入不同類別的參數,卻仍會過?
public class Car<T,E,F>{
private T key;
private T oil;
private E type;
private F kind;
public Car(){ }
public Car(T Key, T oil){
this.key = key;
this.oil = oil;
}
public void printOil(){
System.out.println("這部車要加" + oil.getClass() + "種類的油");
}
public static void main(String[] args){
Car<Number,String,Integer> car1 = new Car<Number,String,Integer>(1,2L);
car1.printOil();
}
}
你的T 是放Number 1 (Integer)和 2L (Float) 都繼承自Number 屬於子型 當然會過