Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleting a class object in java

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?

like image 549
Soroush khoubyarian Avatar asked Jun 28 '26 05:06

Soroush khoubyarian


2 Answers

After you do p = null; the last reference of your point is deleted and the garbage collector collects the instance now because there is no reference to this instance. If you call System.gc(); the garbage collector will recycle unused objects and invoke the finalize methods of this objects.

    Point p = new Point(50,50);
    p = null;
    System.gc();

Output: One point has been destroyed.

like image 63
kai Avatar answered Jun 29 '26 19:06

kai


You cannot delete object in java, thats the work of GC (Garbage Collector) , which finds and deletes unreferenced instance variables. What that means is variables that are no longer pointed or referenced to , which means they have now no way of being called over. Hence when you do this p = null; , you assign a null to the reference variable holding reference to Point object. Hence now Point object that was pointed by p is garbage collectible.

Also according to javadoc for finalize() method,

Called by the garbage collector on an object when garbage collection 
determines that there are no more references to the object. 
A subclass overrides the finalize method
to dispose of system resources or to perform other cleanup.

But there is no guarantee of calling of finalize() method, as GC is not guaranteed to run at a specific time (deterministic time).

like image 29
Mustafa sabir Avatar answered Jun 29 '26 18:06

Mustafa sabir



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!