tags: Java
Comparison 比較
final | finally{} | finalize() | |
---|---|---|---|
keyword | block | method | |
功能 | class:不能繼承 method:不能override variable:常數不能改變 |
不論Exception是否處理,都要執行此區域的程式碼 | 保證物件在被GC之前,完成特定資源的回收作業 Object的一個方法,需override |
final
class FinalExample{
public static void main(String[] args){
final int x=100;
x=200;//Compile Time Error
}
}
finally{}
- 常見使用時機:關閉 JDBC connection、釋放 lock
try{
int x=300;
}catch(Exception e){
System.out.println(e);
}finally{
System.out.println("finally block is executed");
}
finalize()
GC (Garbage Collection)
- 自動刪除不必要的物件
- 垃圾收集器(Garbage Collector)會自行尋找不必要的(垃圾)物件,並清除它
Example
class FinalizeExample{
@Override
protected void finalize() throws Throwable {
System.out.println("finalize called");
}
public static void main(String[] args){
FinalizeExample f1=new FinalizeExample();
FinalizeExample f2=new FinalizeExample();
f1=null;
f2=null;
System.gc();
}
}
- 執行結果:
finalize called
finalize called
Extensive Reading 延伸閱讀
- Java筆記 — final, finally 與 finalize:
https://medium.com/@clu1022/java筆記-final-finally-與-finalize-d72dc66e49eb
Reference 參考資料
- Difference between final, finally and finalize:
https://www.javatpoint.com/difference-between-final-finally-and-finalize - [Java] 喝杯咖啡,聊點 GC(一) – 基礎概念:
https://www.alexleo.click/java-喝杯咖啡,聊點-gc(一)-基礎概念/
沒有留言:
張貼留言