English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Static methods belong to the class, they will be loaded into memory with the class. You can call them without creating an object. (Use the class name as a reference).
public class Sample{ static int num = 50; public static void demo(){ System.out.println("Content of the static method"); } public static void main(String args[]){ Sample.demo(); } }
Output result
Content of the static method
The keyword 'this' is used as a reference to the instance. Since static methods do not belong to any instance, they cannot use 'this' reference in static methods. If it still does, please try this, which will generate a compile-time error.
And the main method is static, so you cannot use 'this' to refer in the main method.
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 error