我們可以在 Java 中丟擲泛型類的物件嗎?


泛型是 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

丟擲泛型類物件

要建立可使用 throws 子句丟擲的自定義類,你需要擴充套件可丟擲類。

class MyException extends Throwable{
   MyException(String msg){
      super(msg);
   }
}

因此,如果你需要丟擲一個通用型別的物件,你應該能夠從其中擴充套件 Throwable 類。但是,如果你嘗試這樣做,將生成編譯時錯誤。因此,你無法使用 throws 子句丟擲泛型類物件。

示例

 例項演示

class Student<T>extends Throwable{
   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[]) {
   }
}

編譯時錯誤

GenericsExample.java:1: error: a generic class may not extend java.lang.Throwable
class Student<T>extends Throwable{
                        ^
1 error

更新時間:09-Sep-2019

555 次瀏覽

開啟 職業生涯

透過完成課程進行認證

開始
廣告
© . All rights reserved.