0

我已经定义了一个对象并声明了一个静态变量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();
    }

}
4

4 回答 4

8

不,只有一个变量——你还没有声明任何实例变量。

不幸的是,Java 允许您访问静态成员,就好像您通过相关类型的引用访问它一样。这是 IMO 的设计缺陷,一些 IDE(例如 Eclipse)允许您将其标记为警告或错误 - 但它是语言的一部分。您的代码实际上是:

System.out.println("Value of i = " + test.i);
System.out.println("Value of static i = " + test.i);

如果您确实通过相关类型的表达式,它甚至不会检查值 - 例如:

test ignored = null;
System.out.println(ignored.i); // Still works! No exception

尽管如此,任何副作用仍在评估中。例如:

// This will still call the constructor, even though the result is ignored.
System.out.println(new test().i);
于 2013-09-26T18:31:41.573 回答
2

该字段i被声明为static。您可以使用或访问static字段。所以两者YourClass.StaticFieldinstance.StaticField

this.i
test.i

test在您的类的实例方法的上下文中引用相同的值。

使用or访问static字段被认为是不好的做法。this.iinstance.i

于 2013-09-26T18:32:06.277 回答
0

static 是类级别变量,非静态是实例变量(对象级别变量)。所以在这里你只声明静态变量并以不同的方式称呼它们,但意义相同。

this.i
test.i

都被视为类级别变量或静态变量。

于 2013-09-26T18:44:32.577 回答
0

您没有在这里声明任何实例变量。只有一个静态变量。如果您声明实例变量而不分配值,那么如果您尝试使用“this”关键字打印该实例变量值,您可以获得默认值为 0。

于 2013-09-26T21:18:33.610 回答