class GenericNumber2 <T extends Integer>{ T number; public void setNumber(T number){ this.number = number; } public T getNumber(){ return number; } } public class GenericsList { public static void main(String[] args) { GenericNumber2 <integer> i = new GenericNumber2 <integer>(); i.setNumber(10); System.out.println("Number value : "+i.getNumber()); } }執行結果
若資料型態想改用Double定義,例如: GenericNumber2 < Double > d = new GenericNumber2 < Double > (); 那麼在編譯時,就會指出下列錯誤
Exception in thread "main" java.lang.Error: Unresolved compilation problems: Bound mismatch: The type Double is not a valid substitute for the bounded parameter另,定義泛型類別of the type GenericNumber2 Bound mismatch: The type Double is not a valid substitute for the bounded parameter of the type GenericNumber2 at GenericsList.main(GenericsList.java:18)
public class GenericClass <T> { ... }就如同以下列方式定義
public class GenericClass <T extends Object > { ... }
沒有留言:
張貼留言