Search code examples
java

How do I delete an object in java?


I want to delete an object I created, (e.g. an oval that follows you), but how would I do this? I ran the statement:

delete follower1;

but it didn't work.

Background:

I'm making a small game with a oval you can control, and a oval which follows you. Now I've got files named: DrawPanel.class, this class draws everything on the screen, and handles collisions, sounds, etc. I also have enemy.class, which is the oval following the player. I also have entity.class, which is the player you can control. And if the player intersects with the follower (the enemy), I want my player object to get deleted. Currently, the way I'm doing it is:

public void checkCollisions(){
    if(player.getBounds().intersects(follower1.getBounds())){
        Follower1Alive = false;
        player.health = player.health - 10;
     }
 }

Solution

  • You should remove the references to it by assigning null or leaving the block where it was declared. After that, it will be automatically deleted by the garbage collector (not immediately, but eventually).

    Example 1:

    Object a = new Object();
    a = null; // after this, if there is no reference to the object,
              // it will be deleted by the garbage collector
    

    Example 2:

    if (something) {
        Object o = new Object(); 
    } // as you leave the block, the reference is deleted.
      // Later on, the garbage collector will delete the object itself.
    

    Not something that you are currently looking for, but FYI: you can invoke the garbage collector with the call System.gc()