Java重要技術(20)泛型之參數化型別的特點

來源:互聯網
上載者:User

標籤: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)泛型之參數化型別的特點

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.