final、finally 和 finalize 在 Java 中


  • 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.

更新於: 29-Jul-2021

11 千次瀏覽

開啟您的 職業生涯

完成課程即獲得認證

開始
廣告
© . All rights reserved.