开发者

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

开发者 https://www.devze.com 2023-01-10 17:43 出处:网络
@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 di

@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?


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
}


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号