Are static members of a generic class different for different types in Java?

耗尽温柔 提交于 2020-01-22 22:52:27

问题


@Spence asked this Previous Question.

So, how's that work in Java? Generic types are discarded at runtime in Java, so what happens to static variables of classes instantiated with different generic types?


回答1:


Static members in Java can't have generic type arguments from the class that contains them.

public class Gen<T> {
  public static T foo; // compiler error
}



回答2:


Static variables are shared among all the instances of that type, even of different type parameters.

From the generics tutorial, page 14:

As consequence, the static variables and methods of a class are also shared among all the instances. That is why it is illegal to refer to the type parameters of a type declaration in a static method or initializer, or in the declaration or initializer of a static variable.



来源:https://stackoverflow.com/questions/3445427/are-static-members-of-a-generic-class-different-for-different-types-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!