Destroying objects in Java

后端 未结 8 752
走了就别回头了
走了就别回头了 2021-01-22 00:07

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

8条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-22 00:51

    Though defining ownership (ground with collection of Moneys, 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

提交回复
热议问题