为什么我们不能在静态方法中使用“this"关键字 [英] Why can't we use 'this' keyword in a static method
问题描述
class Sub {
static int y;
public static void foo() {
this.y = 10;
}
}
我了解 this
表示调用该方法的对象,并且静态方法未绑定到任何对象.但在上述情况下,变量 y 也是静态的.
I understand that this
represents the object invoking the method and that static methods are not bound to any object. But in the above mentioned case, the variable y is also static.
如果我们可以在类对象上调用静态方法,为什么不能让静态方法设置类的静态变量.
If we can invoke static method on class object, why can't we allow static methods to set the static variables of the class.
这个附加约束的目的是什么?
What is the purpose of this additional constraint?
推荐答案
因为 this
指的是对象实例.静态方法的调用中没有对象实例.但是当然你可以访问你的静态字段(只有静态字段!).就用
Because this
refers to the object instance. There is no object instance in a call of a static method. But of course you can access your static field (only the static ones!). Just use
class Sub {
static int y;
public static void foo() {
y = 10;
}
}
如果你想确保你得到的是静态字段 y
而不是一些同名的局部变量,使用类名来指定:
If you want to make sure you get the static field y
and not some local variable with the same name, use the class name to specify:
class Sub {
static int y;
public static void foo(int y) {
Sub.y = y;
}
}
这篇关于为什么我们不能在静态方法中使用“this"关键字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!