Deleting a class object in java

2019-04-14 10:25发布

I have a class named Point as below:

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.");
    } 
}

I have an object from this class named p as below:

Point p = new Point(50,50);

I want to delete this object, I searched how to do it, the only solution I found was:

p = null;

But the finalize method of Point didn't work after I did it. What can I do?

8条回答
beautiful°
2楼-- · 2019-04-14 10:46

You do not need to destroy the object, the garbage collector will do it for you.

查看更多
太酷不给撩
3楼-- · 2019-04-14 10:47

In java there is no such thing as "delete an object". Objects are automatically removed by the garbage collector when it finds that there is no reference to it. The finalize() method is also automatically called by the garbage collector before the object is permanently removed from the memory. You have no control over when this happens.

查看更多
登录 后发表回答