为什么 Java 类的 main 方法中不能使用 this 关键字?

java 8object oriented programmingprogramming更新于 2025/9/21 0:44:17

静态方法属于类,它们会随类一起加载到内存中。无需创建对象即可调用它们(使用类名作为引用)。

示例

public class Sample{
   static int num = 50;
   public static void demo(){
      System.out.println("静态方法的内容");
   }
   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("Contents of the 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 error

相关文章