泛型應用於編譯時還是執行時?


泛型是 Java 中的一個概念,在這裡你可以啟用一個類、介面和方法,將所有(引用)型別作為引數接受。換句話說,它是一個能讓使用者動態選擇方法、類構造器所接受的引用型別。透過將一個類定義為泛型,你可以使其型別安全,即它能對任何資料型別起作用。

示例

 線上演示

class Student<T>{
   T age;
   Student(T age){
      this.age = age;
   }
   public void display() {
      System.out.println("Value of age: "+this.age);
   }
}
public class GenericsExample {
   public static void main(String args[]) {
      Student<Float> std1 = new Student<Float>(25.5f);
      std1.display();
      Student<String> std2 = new Student<String>("25");
      std2.display();
      Student<Integer> std3 = new Student<Integer>(25);
      std3.display();
   }
}

輸出

Value of age: 25.5
Value of age: 25
Value of age: 25

更新時間:09-Sep-2019

530 次檢視

開啟你的職業生涯

完成課程後獲得認證

開始
廣告