I recently started refactoring my Java code. It was all running fine until later on, I noticed that some of my objects lost “proper referencing”, i.e. it became the case that the objects were “passed by value”, and not “passed by reference”. Note that I do understand that Java is always pass-by-value and passing by reference is only emulated by memory address passing (which is why I quote the two phrases).
My question is: is there a difference between
Object o = new Object();
and
Object o = makeMeAnObjectPlease();
where
public Object makeMeAnObjectPlease()
{
Object c = new Object();
return c;
}
And by difference, I mean will o after Object o = makeMeAnObjectPlease() refer to the same memory address as the one created inside makeMeAnObjectPlease()? And are there any more differences?
Yes, it will refer to the same object. No, there are no other differences. To take the example further:
There’s exactly one Date object in that code, though it’s known by different names at different times. In the end, all the names point at the same object, thus in the end, when we print the object out by two different names, you’ll see that they actually indicate the same object in memory, which was modified by the
changeMyObjectPlease()method. An example of running the above is: