Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What difference does instantiating make?

Tags:

java

instance

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).

like image 646
Vic Avatar asked Jan 07 '23 09:01

Vic


2 Answers

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.

like image 164
Mureinik Avatar answered Jan 17 '23 18:01

Mureinik


In Case 1 you:

  • Declare a variable
  • Set the variable to a value

In Case 2 you:

  • Declare a variable
  • Create a new object
  • Set the variable to a value
  • Set the variable to a value
  • Destroy the recently created object

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).

like image 27
David Avatar answered Jan 17 '23 19:01

David