-
Notifications
You must be signed in to change notification settings - Fork 45.4k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
语法糖章节-当泛型内包含静态变量 疑问 #2176
Comments
这块原文确实存在一些问题,欢迎提交一个PR完善一下。 |
提交了一个pr |
当泛型内包含静态变量
原文是:
`当泛型内包含静态变量
public class StaticTest{
public static void main(String[] args){
GT gti = new GT();
gti.var=1;
GT gts = new GT();
gts.var=2;
System.out.println(gti.var);
}
}
class GT{
public static int var=0;
public void nothing(T x){}
}
以上代码输出结果为:2!
由于经过类型擦除,所有的泛型类实例都关联到同一份字节码上,泛型类的所有静态变量是共享的。`
静态变量,本身不就是全局唯一的吗,即使你通过对象访问,本质访问的还是静态变量,这与是否使用泛型没有关系啊。
为了证明这个观点,我去除了泛型,重新执行代码,依然打印2.这是因为:
GT<Integer> gti = new GT<Integer>(); gti.var=1; GT<String> gts = new GT<String>(); gts.var=2;
修改的是同一个变量。
示例如下:
`
public static void main(String[] args) throws Throwable {
class GT{
public static int var=0;
public void nothing(int x){}
}
`
The text was updated successfully, but these errors were encountered: