Kac*_*aye 2 java compiler-errors
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
}
}
Run Code Online (Sandbox Code Playgroud)
编译时,我收到错误:非静态变量,这不能从静态上下文引用.但是,如果我删除"这个".没有错误.我不明白为什么当我使用关键字static清楚地声明它时,月份是非静态变量.
您根本无法this在静态上下文中使用.这是设计 - this指的是对象而不是类.如果您遇到方法参数和字段之间可能存在名称冲突的问题,则可以使用类名:
public static void setMonth(int month)
{
Date.month = month;
}
Run Code Online (Sandbox Code Playgroud)
另一方面,您可以考虑您的设计并重新考虑将整个类用作单个对象的决定.
| 归档时间: |
|
| 查看次数: |
179 次 |
| 最近记录: |