Sor*_*ian 2 java class object-destruction
我有一个名为Point如下的类:
public class Point {
public int x;
public int y;
public Point(int X, int Y){
x = X;
y = Y;
}
public double Distance(Point p){
return sqrt(((this.x - p.x) * (this.x - p.x)) + ((this.y - p.y) * (this.y - p.y)));
}
protected void finalize()
{
System.out.println( "One point has been destroyed.");
}
}
Run Code Online (Sandbox Code Playgroud)
我有一个来自此类的对象,名称p如下:
Point p = new Point(50,50);
Run Code Online (Sandbox Code Playgroud)
我想删除这个对象,我搜索了怎么做,我找到的唯一解决方案是:
p = null;
Run Code Online (Sandbox Code Playgroud)
但是Point的finalize方法在我做了之后就没有用了。我能做什么?
完成后p = null;,您点的最后一个引用被删除,垃圾收集器现在收集该实例,因为没有对该实例的引用。如果调用System.gc();垃圾收集器,将回收未使用的对象并调用此对象的 finalize 方法。
Point p = new Point(50,50);
p = null;
System.gc();
Run Code Online (Sandbox Code Playgroud)
输出: One point has been destroyed.
| 归档时间: |
|
| 查看次数: |
10629 次 |
| 最近记录: |