English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
스타틱 메서드는 해당 클래스에 속하며, 클래스와 함께 메모리에 로드됩니다. 객체를 생성하지 않고도 호출할 수 있습니다. (클래스 이름을 사용하여 참조).
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 에러