Suppose we have a class World
and we've declared an instance dreamWorld
of that class. How Case 1 is different from Case 2 other than it's one line shorter? What difference does instantiating in the second case actually make? I mean, afterall dreamWorld
will be just the same in both cases, right?
Case 1:
void changeWorld(World outerWorld) {
World dreamWorld;
dreamWorld = outerWorld;
}
Case 2:
void changeWorld(World outerWorld) {
World dreamWorld;
dreamWorld = new World();
dreamWorld = outerWorld;
}
where outerWorld
is an object of World
class created elsewhere and, say, provided as a method argument (I'm not sure if it matters how it is being provided).
PS Thank you for all your prompt and helpful replies, guys, and sorry for my delayed gratitude (it took me time to read some literature that I felt would be necessary to fully understand your replies).
Case 2 is pointless. You instantiate a new World
object and then lose the reference to it a line later when you assign dreamWorld = outerWorld
, leaving it for the garbage collector to collect.
EDIT:
As @Rob pointed out, a caveat to the aforementioned statement is in the case that World
's constructor performs some external interaction, instantiating it will still take an affect. Assigning it to dreamWorld
, however, is pointless, as this reference will be lost.
In Case 1 you:
In Case 2 you:
Both methods produce the same end result, but the second one also creates and destroys an object that was never used (which is, of course, entirely superfluous).
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