《瘋狂Java講義》(二十七)----泛型

來源:互聯網
上載者:User

標籤:包含   method   構造器   資訊   方法   log   this   arraylist   end   

  • 菱形文法

List<String> strList = new ArrayList<String>();

Java7 後允許在構造器後不需要帶完整的泛型資訊,只要給出一對角括弧即可。

List<String> strList = new ArrayList<>();

  • 泛型介面/類

可以為任何類/介面增加泛型聲明

class Apple<T> {    private T info;    public Apple() {            }        public Apple(T info) {        this.info = info;    }        public void setInfo(T info) {        this.info = info;    }        public T getInfo() {        return this.info;    }}public class GenericClassDemo {    public static void main(String[] args) {        // TODO Auto-generated method stub        Apple<String> a1 = new Apple<>("Apple");        System.out.println(a1.getInfo());        Apple<Double> a2 = new Apple<>(5.97);        System.out.println(a2.getInfo());    }}

當建立帶泛型聲明的自訂類,為該類定義構造器時,構造器名還是原來的類名,不要增加泛型聲明。例如,Apple<T>,構造器名依然是Apple,不是Apple<T>.

 

  • 從泛型類派生子類

當建立了帶泛型聲明的介面/父類之後,可以為該介面建立實作類別,或從該父類派生子類,但需要指出的是,當使用這些介面/父類時不能在包含類型形參。

class Apple<T> {    protected T info;    public Apple() {            }        public Apple(T info) {        this.info = info;    }        public void setInfo(T info) {        this.info = info;    }        public T getInfo() {        return this.info;    }}class A1 extends Apple<String> {    public A1(String info) {        this.info = info;    }}public class GenericClassDemo {    public static void main(String[] args) {        // TODO Auto-generated method stub        Apple<String> a1 = new Apple<>("Apple");        System.out.println(a1.getInfo());        Apple<Double> a2 = new Apple<>(5.97);        System.out.println(a2.getInfo());                A1 aa1 = new A1("Apple");        System.out.println(aa1.getInfo());    }}

不管為泛型的型別參數傳入哪一種類型實參,對於Java來說,它們依然被當成同一個類處理。因此在靜態方法/靜態初始化塊或者靜態變數的聲明和初始化中不允許使用類型形參。

 

《瘋狂Java講義》(二十七)----泛型

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.