Zac Taylor Zac Taylor - 4 months ago 9
Java Question

New instance of class created or just space in memory allocated?

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
new Fish
is called, is there a new instance of
Fish
floating around somewhere without a reference or have I just allocated memory for a new
Fish
without actually instantiating it?

Can I get the
new Fish
call to create an actual instance of the
Fish
with a unique reference name other than iterating through a loop?

Answer

When new Fish is called, is there a new instance of Fish floating around somewhere without a variable name or have I just allocated memory for a new Fish without actually instantiating it?

A new Fish object will be created, and will be garbage-collected since there is no reference to it. The garbage collection will take place (sometime) after the constructor of Fish is done.
In your case that doesn't make much sense, but sometimes it does, if instantiating an object will start a new Thread or run some other routines that you want to be run only once.

If I have only allocated memory or there is a Fish without a name, how can I get the new Fish call to create an actual instance of the Fish with a unique variable name?

This is not very clear. But I sense that you just want to return new Fish(...); and assign it to a variable yourself where you call it, something like:

Fish babyFish = femaleFish.mate(maleFish);
Comments