Java Generics 简明教程
Java Generics - No Static field
使用泛型时,不允许类型参数为静态类型。由于静态变量在对象之间共享,所以编译器无法确定要使用哪种类型。假设允许静态类型参数,请考虑以下示例。
Using generics, type parameters are not allowed to be static. As static variable is shared among object so compiler can not determine which type to used. Consider the following example if static type parameters were allowed.
Example
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
都具有共享的静态类型变量,因此无法确定其类型。因此,不允许使用静态类型参数。
As stringBox and integerBox both have a stared static type variable, its type can not be determined. Hence static type parameters are not allowed.