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


静态方法属于该类,并且将与类一起加载到内存中。你无需创建对象就可以调用它们(使用类名作为引用)。

示例

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”引用。如果仍然尝试这样做,则会生成编译时错误。

而且,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

更新日期:05-Aug-2019

1K+ 浏览

开启您的 事业

完成课程获取认证

开始
广告
© . All rights reserved.