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.