我们可以在 Java 中抛出泛型类的对象吗?

java 8object oriented programmingprogramming更新于 2024/10/13 12:34:00

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

相关文章