是否可以例項化型別引數在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
廣告
資料結構
網路
關係型資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP