Java 中的 final、finally 和 finalize

java programming java8object oriented programming

  • final 关键字可以与类方法和变量一起使用。final 类不能被继承,final 方法不能被覆盖,final 变量不能被重新分配。

  • finally 关键字用于创建跟在 try 块后面的代码块。finally 代码块始终会执行,无论是否发生异常。使用 finally 块允许您运行任何您希望执行的清理类型语句,无论受保护的代码中发生了什么。

  • finalize() 方法在对象被销毁之前使用,并且可以在对象创建之前调用。

示例 final

public class Tester {
   final int value = 10;

   // 以下是声明常量的示例:
   public static final int BOXWIDTH = 6;
   static final String TITLE = "Manager";
   public void changeValue() {
      value = 12; // 将给出错误
   }
   public void displayValue(){
      System.out.println(value);
   }
   public static void main(String[] args) {
      Tester t = new Tester();
      t.changeValue();
      t.displayValue();
   }
}

输出

Compiler will throw an error during compilation.

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

最终示例

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.

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

相关文章