我們可以在 Java 中的靜態方法中使用“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”引用。如果你仍然嘗試這樣做,就會生成編譯時錯誤。

示例

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 error

更新於: 05-Aug-2019

5K+ 瀏覽量

開啟你的 事業

完成課程即可獲得認證

開始
廣告
© . All rights reserved.