我写了这个测试代码:
class MyProgram
{
int count = 0;
public static void main(String[] args)
{
System.out.println(count);
}
}
Run Code Online (Sandbox Code Playgroud)
但它给出了以下错误:
Main.java:6: error: non-static variable count cannot be referenced from a static context
System.out.println(count);
^
Run Code Online (Sandbox Code Playgroud)
如何让我的方法识别我的类变量?
我一直在寻找明确的答案,我认为我有点得到它,但同时我不太明白该关键字的概念,静态.
这是我做的场景:
package oops;
public class Math {
boolean notNumber = false;
static boolean notString = false;
public static void main(String[] args) {
int num1 = 1;
static int num2 = 1; //doesn't work
Math math = new Math();
math.notNumber = true;
notNumber = true; //doesn't work
notString = true;
}
public void whatever() {
notNumber = true;
}
}
Run Code Online (Sandbox Code Playgroud)
为什么不能在静态方法(或任何方法)中将变量声明为静态?"范围"是什么意思?我知道静态变量与类的特定实例无关,它更像是一个"全局"变量.但是为什么不能在方法(num2)中创建静态变量,但可以使用静态变量(notString)?
当你制作静态变量时,你是否必须在课堂上制作它们?方法不可能?
由于我将notNumber声明为非静态,我知道我必须创建一个对象来访问该变量.但是为什么它在没有任何对象创建的情况下工作,而不是在静态方法main()中?