Java – create new instances of classes or allocate only space in memory?
UPDATE
public Fish mate(Fish other){ if (this.health > 0 && other.health > 0 && this.closeEnough(other)){ int babySize = (((this.size + other.size) /2)); int babyHealth = (((this.health + other.health) /2)); double babyX = (((this.x + other.x) /2.0)); double babyY = (((this.y + other.y) /2.0)); new Fish (babySize,babyHealth,babyX,babyY); } return null; }
When a new fish is called, does a new fish instance float where there is no reference, or do I only allocate memory for the new fish without actually instantiating it?
Can I get a new fish call to create an actual instance of fish with a unique reference name instead of an iterative loop?
Solution
A new fish object will be created and garbage collected because there is no reference to it Garbage collection will take place after the constructor of fish is completed (some time) In your case, it doesn't make much sense, but sometimes it does. If you instantiate an object, it will start a new thread or run some other routines you want to run only once
This is not very clear But I think you just want to return to the new fish (...); And assign it to a variable where you call it, for example:
Fish babyFish = femaleFish.mate(maleFish);