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?
To allocate memory to an object, we must use new(). So the object is always allocated memory on the heap (See this for more details). There are two ways to create an object of string in java: By string literal.
Once the object/instance of type class is define, the class member will occupy some space in memory.
object allocated in heap memory. when object are allocated the slot for all the instance variable is created and destroyed when the object are destroyed.so instance variable is also allocated in heap memory. And the local variable are created in stack at the time when the method are called.
How much memory will be allocated for an object of class given below? Explanation: The size of an object of the class given in question will be of size 22 bytes. This is because the size of an object is always equal to the sum of sizes of the data members of the class, except static members.
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 newFish
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 newFish
call to create an actual instance of theFish
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With