相关疑难解决方法(0)

无法从静态上下文引用非静态变量

我写了这个测试代码:

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)

如何让我的方法识别我的类变量?

java variables compiler-errors non-static

272
推荐指数
7
解决办法
61万
查看次数

STATIC变量的概念和Java中的方法

我一直在寻找明确的答案,我认为我有点得到它,但同时我不太明白该关键字的概念,静态.

这是我做的场景:

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)
  1. 为什么不能在静态方法(或任何方法)中将变量声明为静态?"范围"是什么意思?我知道静态变量与类的特定实例无关,它更像是一个"全局"变量.但是为什么不能在方法(num2)中创建静态变量,但可以使用静态变量(notString)?

  2. 当你制作静态变量时,你是否必须在课堂上制作它们?方法不可能?

  3. 由于我将notNumber声明为非静态,我知道我必须创建一个对象来访问该变量.但是为什么它在没有任何对象创建的情况下工作,而不是在静态方法main()中?

java static scope

5
推荐指数
1
解决办法
144
查看次数

标签 统计

java ×2

compiler-errors ×1

non-static ×1

scope ×1

static ×1

variables ×1