使用泛型时,类型参数不允许为静态变量,由于静态变量在对象之间共享,因此编译器无法确定要使用哪种类型。
package com.learnfk; 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> { //编译器错误 private static T t; public void add(T t) { this.t = t; } public T get() { return t; } }
由于stringBox和integerBox都有一个带有标签的静态类型变量,因此无法确定其类型。因此,不允许使用静态类型参数。
链接:https://www.learnfk.comhttps://www.learnfk.com/java-generics/java-generics-no-static.html
来源:LearnFk无涯教程网
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)