Java 泛型 - 無靜態欄位



使用泛型時,不允許型別引數為靜態。由於靜態變數在物件之間共享,因此編譯器無法確定要使用哪種型別。如果允許靜態型別引數,請考慮以下示例。

示例

package com.tutorialspoint;

public class GenericsTester {
   public static void main(String[] args) {
      Box<Integer> integerBox = new Box<Integer>();
	  Box<String> stringBox = new Box<String>();
	  
      integerBox.add(new Integer(10));
      printBox(integerBox);
   }

   private static void printBox(Box box) {
      System.out.println("Value: " + box.get());
   }  
}

class Box<T> {
   //compiler error
   private static T t;

   public void add(T t) {
      this.t = t;
   }

   public T get() {
      return t;
   }   
}

由於 stringBox 和 integerBox 都具有一個已啟動的靜態型別變數,因此無法確定其型別。因此,不允許使用靜態型別引數。

廣告