使用泛型时,类型参数不允许为静态(static)。由于静态变量在对象之间共享,因此编译器无法确定要使用的类型。如果允许静态类型参数,请考虑以下示例。
示例
创建一个名称为:NoStaticField.java 文件,并编写以下代码 -
package com.zaixian.demo6;
public class NoStaticField {
    public static void main(String[] args) {
        Box<Integer> integerBox = new Box<Integer>();
        Box<String> stringBox = new Box<String>();
        integerBox.add(new Integer(1991));
        printBox(integerBox);
    }
    private static void printBox(Box box) {
        System.out.println("Value: " + box.get());
    }
}
class Box<T> {
    // compiler error - 错误的用法
    // private static T t;
    // 正确的用法
    private T t;
    public void add(T t) {
        this.t = t;
    }
    public T get() {
        return t;
    }
}
由于stringBox和integerBox都有一个静态类型变量,它的类型无法确定。 因此,不允许使用静态类型参数。
						上一篇:
								Java泛型不能使用实例
												下一篇:
								Java泛型不能转换类型
												
						
						
					
					
					