public class example {
int a = 0;
public void m() {
int b = this.a;
}
public static void main(String[] args) {
int c = this.a;
}
}
私はJavaが初めてです。main メソッドで「this」を使用できないのはなぜですか?
public class example {
int a = 0;
public void m() {
int b = this.a;
}
public static void main(String[] args) {
int c = this.a;
}
}
私はJavaが初めてです。main メソッドで「this」を使用できないのはなぜですか?
this現在のオブジェクトを参照します。ただし、mainメソッドは静的です。つまり、オブジェクト インスタンスではなくクラスにアタッチされているため、内部に現在のオブジェクトはありませんmain()。
を使用するには、クラスのインスタンスthisを作成する必要があります (実際、この例では、別のオブジェクト参照があるため使用しません。ただし、メソッド内でthis使用することもできます。オブジェクトのコンテキストに住んでいます):thism()m()
public static void main(String[] args){
example e = new example();
int c=e.a;
}
ところで、Java の命名規則に慣れておく必要があります。通常、クラス名は大文字で始まります。
example のインスタンスを作成する必要があります
example e = new example()
e.m()
public class Example {
int a = 0;
// This is a non-static method, so it is attached with an instance
// of class Example and allows use of "this".
public void m() {
int b = this.a;
}
// This is a static method, so it is attached with the class - Example
// (not instance) and so it does not allow use of "this".
public static void main(String[] args) {
int c = this.a; // Cannot use "this" in a static context.
}
}
メインなのでstatic。アクセスaするには、それも宣言する必要がstaticあります。静的変数は、クラスのインスタンスなしで存在します。非静的変数はインスタンスが存在する場合にのみ存在し、各インスタンスには という名前の独自の属性がありますa。
メソッドは静的です。mainつまり、exampleクラスをインスタンス化せずに呼び出すことができます(静的メソッドはClassメソッドとも呼ばれます)。これは、のコンテキストでmainは、変数aが存在しない可能性があることを意味します(exampleインスタンス化されたオブジェクトではないため)。同様に、最初にインスタンス化せずにmから呼び出すことはできません:mainexample
public class example {
int a=0;
public void m(){
// Do stuff
}
public static void main(String[] args){
example x = new example();
x.m(); // This works
m(); // This doesn't work
}
}
アンドレアスからのコメントに加えて
「a」を使用したい場合。次に、新しい例をインスタンス化する必要があります [例のクラス名を大文字の Eaxmple にすることをお勧めします]。
何かのようなもの
public static void main(String[] args) {
Example e = new Example();
int c = e.a;
}
HTH