繁体   English   中英

对Java的误解

[英]Misunderstanding in Java

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

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”都是非静态的!

您试图访问a以静态方式。 首先你需要实例main访问a

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

另外,为了便于阅读,您应该大写类的名称,并用驼峰式大小写实例变量。

变量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

    }
}

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

您尚未在nn()方法中初始化main的实例。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM