final,finally,finalize的区别
final 是一个修饰符,可以用来修饰:
类:类不可以被继承
方法:方法不可以被继承
变量:值一旦初始化之后不可再改变finally: 和try …catch 配合使用,通常用于做最后的资源释放
finally 和return 同时出现:
public class FinallyReturnDemo {
public static void main(String[] args) {
FinallyReturnDemo demo = new
FinallyReturnDemo();
int i = demo.test(10);
System.out.println(i);
}
public int test(int a){
try{
int b=0;
System.out.println(a/b);
return a;
}catch(Exception e){
a = 20;
return a;
}finally {
a = 30;
}
}
}
运行结果: 20
3 . finalize() :是Object类中的方法
作用:GC 在回收对象之前,默认会调用对应对象中的该方法用于做最后的资源释放
GC 回收对象 :
System.gc()
public class Person {
@Override
protected void finalize() throws Throwable {
System.out.println("最后的资源释放");
}
}
测试类
public class FlinalizeDemo {
public static void main(String[] args) {
Person per = new Person();
//使用per对象
per = null;
//让其立即被回收
System.out.println("开始回收");
System.gc();
}
}