Java 中的 final、finally 和 finalize


  • final 關鍵字可以用在類方法和變數上。final 類不能被繼承,final 方法不能被重寫,final 變數不能被重新賦值。

  • finally 關鍵字用於建立一個跟在 try 塊之後的程式碼塊。無論是否發生異常,finally 程式碼塊總是被執行。使用 finally 塊可以在任何情況下都執行一些清理語句,無論受保護程式碼中發生了什麼。

  • finalize() 方法在物件被銷燬之前使用,並且可以在物件建立之前呼叫。

final 示例

public class Tester {
   final int value = 10;

   // The following are examples of declaring constants:
   public static final int BOXWIDTH = 6;
   static final String TITLE = "Manager";
   public void changeValue() {
      value = 12; // will give an error
   }
   public void displayValue(){
      System.out.println(value);
   }
   public static void main(String[] args) {
      Tester t = new Tester();
      t.changeValue();
      t.displayValue();
   }
}

輸出

編譯器在編譯期間會丟擲一個錯誤。

Tester.java:9: error: cannot assign a value to final variable value
value = 12; // will give an error
^
1 error

finally 示例

public class Tester {
   public static void main(String[] args) {

      try{
         int a = 10;
         int b = 0;
         int result = a/b;
      }catch(Exception e){
         System.out.println("Error: "+ e.getMessage());
      }
      finally{
         System.out.println("Finished.");
      }
   }
}

輸出

Error: / by zero
Finished.

finalize 示例

public class Tester {
   public void finalize() throws Throwable{
      System.out.println("Object garbage collected.");
   }
   public static void main(String[] args) {

      Tester t = new Tester();
      t = null;
      System.gc();
   }
}

輸出

Object garbage collected.

更新於: 2021 年 7 月 29 日

11000 多次瀏覽

開啟你的職業

完成課程以獲得認證

開始
廣告
© . All rights reserved.