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

Java의 클래스의 main 메서드는 this 키워드를 사용할 수 없는 이유는 무엇인가요?

정적 메서드는 클래스에 속하며, 클래스와 함께 메모리에 로드됩니다. 객체를 생성하지 않고도 호출할 수 있습니다. (클래스 이름을 참조하여 사용).

예제

public class Sample{
   static int num = 50;
   public static void demo(){
      System.out.println("static method的内容");
   }
   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的内容"+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 에러

당신이 좋아할 수 있는