I was talking with my teacher, and she mentioned that an object variable (she means an instance of an object) did not contain the object itself, but rather the address in memory.
I’ve heard that in Java, an instance of an object really contains a reference to an object in memory. Am I wrong? Is a reference the same thing as containing the address in memory, or something else?
An object variable isn’t the same as an instance of an object. It’s really important that you distinguish between variables, their values, and objects.
For example:
The variable is
x. It’s like a piece of paper, which can have a value written on it.The value of the variable is a reference – some data that the VM can use to get to the string object itself. It doesn’t have to be an address – it’s just “a way of getting to the object data”. (For more on this, read Eric Lippert’s blog post “References are not addresses” – that’s talking about C# rather than Java, but it’s the same principle.)
The object itself is a separate entity.
To use a real-world example, imagine I have a piece of paper with my home address written on it. There are clearly three things here:
This becomes important when you consider things like parameter passing and variable assignment. For example:
Here we have two variables,
xandy, like two pieces of paper. We build a house, and write down the directions to it onx. We then copy the value that’s written onxintoy. Note that they’re still completely separate bits of paper – but they currently have the same value written on them. There’s only a single object – we’ve only built one house – but now two pieces of paper have the same directions on them.If one person followed the directions on piece of paper
xand painted the front door red, then a second person followed the directions on piece of papery, they’d find a house with a red front door.On the other hand, if one person scribbled out the directions on piece of paper
x, that wouldn’t affect the directions written on piece of paperyat all.