是否可以实例化类型参数在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

实例化类型参数

我们用来表示对象类型的参数称为类型参数。简而言之,就是在类声明中<>之间声明的参数。在上面的例子中,T是类型参数。

由于类型参数不是类或数组,因此您无法实例化它。如果您尝试这样做,将生成编译时错误。

示例

在下面的Java示例中,我们创建了一个名为**Student**的泛型类,其中T是泛型参数,稍后在程序中我们将尝试使用new关键字实例化此参数。

 在线演示

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();
      T obj = new T();
   }
}

编译时错误

编译时,上述程序会生成以下错误。

GenericsExample.java:15: error: cannot find symbol
      T obj = new T();
      ^
   symbol: class T
   location: class GenericsExample
GenericsExample.java:15: error: cannot find symbol
      T obj = new T();
                  ^
   symbol: class T
   location: class GenericsExample
2 errors

更新于:2019年9月9日

4K+ 次浏览

开启您的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.