Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to destroy object in itself

Tags:

Is there any solution for destroying current instance of object in itself ?

I am looking for something which looks like:

class KillMe {     ....     public void destroy() {         this.getObject = null //this is only for demonstrate my idea     }      .... } 
like image 373
Smolda Avatar asked Jul 20 '11 19:07

Smolda


People also ask

Can an object destroy itself?

A self-destruct is a mechanism that can cause an object to destroy itself or render itself inoperable after a predefined set of circumstances has occurred. Self-destruct mechanisms are typically found on devices and systems where malfunction could endanger large numbers of people.

How can an object remove itself?

No, objects cannot suicide. Any reference of itself is just a reference. To "clear" the object within itself one would just clear all instance variables. To "clear" the object outside itself one would set the variable equal to null.

Can you destroy an object in Java?

Java doesn't let you destroy objects. Any unreachable object may (or may not) be GCed at any particular point in time.


2 Answers

Java objects live until there are no longer any references to them. Since an object cannot determine how many references there are to itself, an object cannot "destroy itself".

like image 65
Greg Hewgill Avatar answered Sep 17 '22 16:09

Greg Hewgill


The object doesn't have access to the references to it so there's no way to set them to null or something else. An object can only be "destroyed" when the garbage collector comes around and clears out all unreferenced objects.

That being said, try this:

public void destroy() {     System.exit( 0 ); } 
like image 31
tskuzzy Avatar answered Sep 18 '22 16:09

tskuzzy