The object variable does not match the instance of the object. It is very important to distinguish between variables, their values ​​and objects.
For instance:
String x = "hello";
Variable x . It is like a piece of paper on which a value can be written.
The value of the variable is a reference — some data that the VM can use to access the object itself as a string. It doesn’t have to be an address - it’s just a “way to get to the object’s data” (For more on this, read Eric Lippert's blog, “Links are not addresses” - this is talking about C #, not Java, but it's the same principle.)
The object itself is a separate object.
To use a real-life example, imagine that I have a piece of paper with my home address written on it. There are three things here:
- Paper (as a variable). The paper itself is not my home address, and it is not a home. It is just that which can hold value.
- My home address is not a piece of paper and is not a home. This is just a value that allows someone to get to my house.
- My home is neither a sheet of paper nor an address in itself. This is an object.
This becomes important if you consider things like passing parameters and assigning variables. For instance:
House x = new House("Jon"); House y = x;
Here we have two variables, x and y , like two sheets of paper. We build a house and write it on x . Then we copy the value that is written in x to y . Note that they are still completely separate pieces of paper - but they currently have the same meaning written on them. There is only one object - we built only one house, but now it has the same directions as on two sheets.
If one person followed the directions on sheet of paper x and painted the front door in red, then the second person followed the directions on sheet of paper y , they will find a house with a red front door.
On the other hand, if one person scribbled directions on sheet of paper x , this would not affect the directions written on sheet of paper y at all.
source share