【发布时间】:2013-09-27 05:18:33
【问题描述】:
我已经定义了一个对象并声明了一个静态变量i。在get() 方法中,当我尝试打印实例和类变量时,都打印相同的值。
this.i 不是实例变量吗?它应该打印 0 而不是 50?
public class test {
static int i = 50;
void get(){
System.out.println("Value of i = " + this.i);
System.out.println("Value of static i = " + test.i);
}
public static void main(String[] args){
new test().get();
}
}
【问题讨论】:
-
static变量是在类级别而非实例上声明的。对于每个实例,它总是相同的。可以引用为this.VARIABLE或Type.Variable。 -
顺便说一句,即使对于测试代码,最好遵循命名约定。如果你的班级被称为
Test而不是test,那么发生的事情会更明显。
标签: java