English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Javaの静的メソッドではthisキーワードを使用できますか?

静的メソッドはそのクラスに属しており、クラスとともにメモリにロードされます。オブジェクトを作成せずに呼び出すことができます。(クラス名を使用して参照)。

サンプル

public class Sample{
   static int num = 50;
   public static void demo(){
      System.out.println("Contents of the static method");
   }
   public static void main(String args[]){
      Sample.demo();
   }
}

出力結果

Contents of the static method

キーワード「this」はインスタンスへの参照として使用されます。静的メソッドはどのインスタンスにも属さないため、したがって、静的メソッドでは「this」を参照することはできません。もしこれでも同じであれば、このように試してみてください。これによりコンパイル時エラーが生成されます。

サンプル

public class Sample{
   static int num = 50;
   public static void demo(){
      System.out.println("Contents of the static method"+this.num);
   }
   public static void main(String args[]){
      Sample.demo();
   }
}

コンパイル時エラー

Sample.java:4: error: non-static variable this cannot be referenced from a static context
   System.out.println("Contents of the static method"+this.num);
                                                      ^
1 エラー
おすすめ