finalize方法
系统自动调用finalize方法,回收那些没有引用指向的java对象(垃圾数据),如果需要释放资源,可以在该方法中释放
源码如下,并无方法体
protected void finalize() throws Throwable { }
可以重写finalize方法
public class FinalizeTest {
public static void main(String[] args) {
Student3 s3=new Student3(15, "ZhangSan");
System.out.println(s3.age);
s3=null;//没有引用指向它,等待回收
System.gc();//建议系统回收垃圾
}
}
class Student3{
int age;
String name;
public Student3(int age, String name) {
super();
this.age = age;
this.name = name;
}
@Override
protected void finalize() throws Throwable {
// TODO Auto-generated method stub
//super.finalize();
System.out.println("the Student3 object is over");
//让引用再次重新指向该对象,该对象不是垃圾数据,不会被垃圾回收器回收!
//Student3 s=this;
}
}
out:
15
the Student3 object is over
转载:http://www.monkey1024.com/javase/341