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

これはクラス変数ではないため、a を変更するにはクラス main のインスタンスが必要です。

于 2012-08-01T00:37:34.940 に答える
0

メソッドmainでのインスタンスを初期化していません。nn()

于 2012-08-01T00:37:59.017 に答える