Null an object within itself?

Auryg

Platinum Member
Dec 28, 2003
2,377
0
71
I'm writing a cell phone game and I have an enemy class, and in that class I'd like to have a die() function where that specific object nulls itself out.

So like I'd go Enemy blah = new Enemy();
blah.die()

And then blah would = null..is there any way to do that?
 

mundane

Diamond Member
Jun 7, 2002
5,603
8
81
Once there are no more references to the object, the garbage collector will eventually reclaim the memory.
 

Auryg

Platinum Member
Dec 28, 2003
2,377
0
71
I know that, but I'd like to somehow get rid of the references to it from within the object.
 

Thyme

Platinum Member
Nov 30, 2000
2,330
0
0
You can't force garbage collection, so I don't really know what you want. If blah is still in scope, set blah=null and it will eventually go away.
 

Auryg

Platinum Member
Dec 28, 2003
2,377
0
71
Hmm, I must suck at explaining it. I'll find a way around it. Thanks for the help.
 

Templeton

Senior member
Oct 9, 1999
467
0
0
Something like this should accomplish what you want. I haven't done java in a while, so syntax might suck.
 

Matthias99

Diamond Member
Oct 7, 2003
8,808
0
0
Originally posted by: Templeton
Something like this should accomplish what you want. I haven't done java in a while, so syntax might suck.

Well, I guess that would work if you really had no other way to remove the reference.

I feel like if you can't figure out how to correctly remove all the references to the object, you are probably doing something wrong architecturally in your program. If you do something like the solution described above (where calling Enemy.die() will free the EnemyImpl object), but you don't clear the pointers to the 'shell' class, you'll either leak memory or have problems later if something tries to call a real method on that class.