问题描述
我定义了一个对象并声明了一个静态变量 i
。在 get()
方法中,当我尝试打印实例和类变量时,两者都打印相同的值。
I have defined an object and declared a static variable i
. In the get()
method, when I try to print the instance and class variable, both print the same value.
不是 this.i
一个实例变量?它应该打印0而不是50吗?
Isn't this.i
an instance variable? Should it print 0 instead of 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();
}
}
推荐答案
不,只有一个变量 - 你没有声明任何实例变量。
No, there's only one variable - you haven't declared any instance variables.
不幸的是,Java允许你访问静态成员,就像你通过一个访问它一样相关类型的参考。这是一个设计缺陷IMO,一些IDE(例如Eclipse)允许您将其标记为警告或错误 - 但它是语言的一部分。您的代码是有效的:
Unfortunately, Java lets you access static members as if you were accessing it via a reference of the relevant type. It's a design flaw IMO, and some IDEs (e.g. Eclipse) allow you to flag it as a warning or an error - but it's part of the language. Your code is effectively:
System.out.println("Value of i = " + test.i);
System.out.println("Value of static i = " + test.i);
如果你做通过相关类型的表达式,它不会甚至检查值 - 例如:
If you do go via an expression of the relevant type, it doesn't even check the value - for example:
test ignored = null;
System.out.println(ignored.i); // Still works! No exception
但仍会评估任何副作用。例如:
Any side effects are still evaluated though. For example:
// This will still call the constructor, even though the result is ignored.
System.out.println(new test().i);
这篇关于静态变量与非静态变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!