Java 泛型為何不能用於靜態方法?


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

靜態方法的泛型

我們可以在靜態方法中使用泛型

 線上演示

public class GenericMethod {
   static <T>void sampleMethod(T[] array) {
      for(int i=0; i<array.length; i++) {
         System.out.println(array[i]);
      }
   }
   public static void main(String args[]) {
      GenericMethod obj = new GenericMethod();
      Integer intArray[] = {45, 26, 89, 96};
      sampleMethod(intArray);
      String stringArray[] = {"Krishna", "Raju", "Seema", "Geeta"};
      sampleMethod(stringArray);
      Character charArray[] = {'a', 's', 'w', 't'};
      sampleMethod(charArray);
   }
}

輸出

45
26
89
96
Krishna
Raju
Seema
Geeta
a
s
w
t

我們不能在泛型類的型別引數前使用 static。

示例

 線上演示

class Student<T>{
   static 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();
   }
}

編譯時錯誤

GenericsExample.java:3: error: non-static type variable T cannot be referenced from a static context
      static T age;
            ^
1 error

更新於:09-9-2019

4K+ 訪問

啟動你的 事業

透過完成課程獲得認證

開始
廣告
© . All rights reserved.