TestStatic
public class TestStatic {
static int a;
int b;
static int c;
public int aMethod(){
a++;
return a;
}
public int bMethod(){
b++;
return b;
}
public int cMethod(){
c++;
return c;
}
public static void main(String[] args) {
TestStatic test1 = new TestStatic();
TestStatic test2 = new TestStatic();
TestStatic test3 = new TestStatic();
test1.aMethod();
System.out.println(test1.aMethod());
test2.bMethod();
System.out.println(test2.bMethod());
test3.cMethod();
System.out.println(test3.cMethod());
}
}
结果输出 :
2
2
2
解析:
没有赋值,默认初始化值都为0
调用两次方法,进行两次++运算
所以结果都为2
Java静态变量与实例变量详解
本文通过一个Java示例代码,深入解析了静态变量与实例变量的区别。演示了静态变量在不同对象间共享,而实例变量每个对象独立拥有。通过调用方法,观察变量的递增过程,清晰展示变量作用域和生命周期。
340

被折叠的 条评论
为什么被折叠?



