Java中的靜態方法或靜態程式碼塊有哪些限制?


靜態方法和靜態塊

靜態方法屬於類,它們將與類一起載入到記憶體中,無需建立物件即可呼叫它們。(使用類名作為引用)。

而**靜態塊**是用static關鍵字修飾的程式碼塊。通常,它們用於初始化靜態成員。JVM在類載入時,在main方法之前執行靜態塊。

示例

 線上演示

public class Sample {
   static int num = 50;
   static {
      System.out.println("Hello this is a static block");
   }
   public static void demo() {
      System.out.println("Contents of the static method");
   }
   public static void main(String args[]) {
      Sample.demo();
   }
}

輸出

Hello this is a static block
Contents of the static method

靜態塊和靜態方法的限制

靜態方法

  • 不能從靜態上下文中訪問非靜態成員(方法或變數)。

  • this和super不能在靜態上下文中使用。

  • 靜態方法只能訪問靜態型別資料(靜態型別例項變數)。

  • 不能重寫靜態方法,只能隱藏它。

靜態塊

  • 不能從靜態塊中返回任何值。

  • 不能顯式呼叫靜態塊。

  • 如果靜態塊中發生異常,必須將其包裝在try-catch對中,不能丟擲它。

  • 不能在靜態塊內使用this和super關鍵字。

  • 對於靜態塊,不能動態控制執行順序,它們將按宣告順序執行。

更新於:2019年10月14日

4K+ 瀏覽量

啟動您的職業生涯

透過完成課程獲得認證

開始
廣告