Java finalize() 方法

Java 允许定义这样的方法,它在对象被垃圾收集器析构(回收)之前调用,这个方法叫做 finalize( ),它用来清除回收对象。

例如,你可以使用 finalize() 来确保一个对象打开的文件被关闭了。

在 finalize() 方法里,你必须指定在对象销毁时候要执行的操作。

 

public class main {
    public static void main(String args[]){
        Get g1 = new Get(1);
        Get g2 = new Get(2);
        Get g3 = new Get(3);

        g2 = g3 = null;
        System.gc();
    }
}
class Get extends Object {
    private int id ;
    public Get(int id) {
        this.id = id;
        System.out.println("Object " + id + " is created.");
    }
    protected void finalize() throws java.lang.Throwable {
        super.finalize();
        System.out.println("Object " + id + " is disposed.");
    }
}

猜你喜欢

转载自blog.csdn.net/YiLiXiaoHuiChen/article/details/82941426