I have a general idea of how the Garbage Collector works in Java, but my reasoning for destroying an object is not because I care about freeing up memory, but because of functio
Though defining ownership (ground with collection of Money
s, wallet as collection, or owner attribute for money) could be theoretically cleaner solution, I can easily imagine situation when this is overkill.
For example, it could be completely irrelevant where person have taken his money. And once money have been taken the game don't care who posses that instance of Money
I suggest to simply add isPicked
attribute:
public class Money {
private final int value;
private boolean _isPicked = false;
public Money(double x) {
this.value = x;
}
public boolean isPicked(){
return _isPicked;
}
public void addTo(Person bob) {
if( this.isPicked )
throw new Exception("some message for developers");
bob.addToWallet(this.value);
_isPicked = true;
}
public static void main(String[] args) {
Person bob = new Person();
Money dollar = new Money(1.00);
dollar.addTo(bob); // bob finds $1.00
// dollar = null; // don't need this anymore
Person alice = new Person();
dollar.addTo( alice ); // <------ RUNTIME EXCEPTION
}
}
Doing dollar = null
will result in exception too, but it's less safe, because you can simply forget to do it, or accidentally copy reference to another variable