English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
静的方法はクラスに属し、クラスとともにメモリにロードされます。オブジェクトを作成せずに呼び出すことができます。(クラス名を使用して参照)。
public class Sample{ static int num = 50; public static void demo(){ System.out.println("static method content"); } public static void main(String args[]){ Sample.demo(); } }
出力結果
静的方法の内容
キーワード「this」はインスタンスへの参照として使用されます。静的方法はいかなるインスタンスにも属さないため、静的方法ではthisの参照を使用することはできません。もしそうする場合は、以下のように試してください。これにより、コンパイル時エラーが発生します。
また、mainメソッドは静的であり、したがって、mainメソッドではthisを使用して参照することはできません。
public class Sample{ int num = 50; public static void main(String args[]){ System.out.println("main method content"+this.num); } }
Sample.java:4: error: non-static variable this cannot be referenced from a static context System.out.println("Contents of the main method"+this.num); ^ 1 エラー