2

我正在尝试静态和非静态方法和字段。我试图编译这个:

class main{
    public int a=10;
    static int b=0;
    public static void main(String[] args){
        b+=1; //here i can do anything with static fields.
    }
}

class bla {
    void nn(){
        main.a+=1; //why here not? the method is non-static and the field "main.a" too. Why?
    }
}

编译器返回我:

try.java:10: non-static variable a cannot be referenced from a static context

但为什么?方法和字段“a”都是非静态的!

4

4 回答 4

2

您正在尝试以a静态方式访问。您首先需要实例化main才能访问a.

main m = new main();
m.a += 1;

此外,为了便于阅读,您应该将类​​的名称大写,并将实例变量大写。

于 2012-08-01T00:40:52.647 回答
2

该变量a不是静态的,因此如果没有Main

Main.b += 1; // This will work, assuming that your class is in the same package

Main main = new Main();
main.a += 1; // This will work because we can reference the variable via the object instance

所以,假设我们有这个类

public class Main {

    public int a = 10;
    static int b = 0;

}

现在我们一起来,假设这些类在同一个包中

public class Blah {

    void nn() {

        Main.a += 1; // This will fail, 'a' is not static
        Main.b += 1; // This is fine, 'b' is static

        Main main = new Main();
        main.a += 1; // Now we can access 'a' via the Object reference

    }
}
于 2012-08-01T00:41:00.887 回答
0

您需要一个 main 类的实例来更改 a 因为它不是类变量。

于 2012-08-01T00:37:34.940 回答
0

您尚未mainnn()方法中初始化 的实例。

于 2012-08-01T00:37:59.017 回答