我查看了为什么在引用静态方法中的字段时不能使用关键字“this”?
并认为通过引用变量访问静态成员是可以的,但使用this
访问此类成员是不行的。看看下面的代码。
static int month;
public static void setMonth(int x)
{
Date date = new Date();
date.month = x; //fine, why ?
this.month = x; //compiler error, why ?
}
它清楚地表明它this
与参考变量不同。如果是这样,那么它到底是什么?我需要理解它的真正含义,this
才能理解为什么它不能从静态上下文中访问。
请不要给我指向随机博客或 oracle 教程的链接,这些链接说this
不能从静态上下文中使用——我已经知道了。我想超越这一点,了解为什么不能使用它。
链接问题中的代码 -
public class Date
{
static int month;
public static void setMonth(int x)
{
this.month = x; //compiler error
}
public static int getMonth()
{
return month; //compiles just fine, no error
}
}