標籤:others 引用 strong sys 文法 out amp object code
1.1. 參數化型別的特點
參數化型別有以下特點:
(1)參數化型別和沒有型別參數的原始類型在編譯後沒有本質區別。
(2)型別參數不同的兩個參數化型別,不能混用。
public class GenericParameterTest { //參數化型別T,可以為String,Integer等參考型別。static class Sample<T> { //不帶參數的建構函式。public Sample(){this.obj = null;}public Sample(T obj){this.obj = obj;} //參數化型別作為傳回值的類型。public T work(){System.out.println("work:"+this.obj);return this.obj;} //參數化型別作為參數的類型。public void update(T obj){this.obj = obj;} //參數化型別作為屬性的類型。private T obj; } public static void main(String[] args) { //語法錯誤。錯誤用法。//Sample<int> anotherSample = new Sample<int>(1); //正確用法。T是Integer.Sample<Integer> anotherSample = new Sample<Integer>(1); //正確用法:不使用型別參數,相當於Sample<String>。 //此時可以推匯出型別參數為String。Sample sam = new Sample("Hello"); //錯誤用法,不能將String轉化為Integer.//Integer result = sample.work(); //正確用法。String work();String result = sample.work(); //原始類型。相當於Sample<Object>但是不同於Sample<Object>。 //此時只能推匯出型別參數為Object。Sample sa = new Sample();//錯誤用法,不能將Object轉化為String.//String res = sa.work(); //正確用法。Object work();Object res = sa.work(); }
Java重要技術(20)泛型之參數化型別的特點