一个对象是由产生 到使用 到销毁的过程
即C++中 构造函数-> body->析构函数
在Java之中为了回收不需要的空间可以使用System类的finalize()
class A{
public A(){
System.out.println("A产生了!");
}
public void finalize(){
System.out.println("A消亡了!");
}
}
public class Thrd{
public static void main(String[] args) {
A a=new A();
a=null;//指向了其他,产生了垃圾
System.gc();//手工回收垃圾
}
}
结构:protected void finalize()Throws Throwable{}
抛出的是Throwable(Error+Exception)也就是说不管是否有异常,都会讲这个对象消亡
抛出异常测试:
class A{
public A(){
System.out.println("A产生了!");
}
protected void finalize() throws Throwable{
System.out.println("A消亡了!");
throw new Exception("产生了异常");//实例化异常类+抛出异常信息
}
}
public class Thrd{
public static void main(String[] args) {
A a=new A();
a=null;//指向了其他,产生了垃圾
System.gc();//手工回收垃圾
}
}
异常并没有抛出
final finally finalize区别
final关键字 定义最终类,常量
finally异常的出口
finalize对象回收的的方法,即使出现异常也不会影响执行