為什麼在 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+ 瀏覽

開啟您的 事業

完成課程獲取認證

開始
廣告