I'm learning Java and I have a question about data types.
A variable of primitive type stores a single value. When I assign a new one to it, the old value is lost.
Now with the variables by reference I propose an example, I have a class called Auto
, with an instance variable, called Color
.
If I create two objects of that class, they would both point to "the same" in memory, but each would hold a separate copy of the instance variable, so I can change the Color value on one object, without affecting the other. . However, if I destroy the object, the references to both would be lost (I assume they would point back to null
).
Is this concept I have correct?
To complement @NaCl's good answer , I think this part is left as doubt:
Let's design the classes
Auto
andColor
:You can only create new instances of an object using the word
new
. By creating two instances usingnew
and assigning them to different variables, the variables will point to different memory locations. This can be seen in the image:If we use the same instance of
Color
in both instances ofAuto
, the result will be as follows:If you were to change the color value in another of them, only the other one would be affected:
When you use a primitive type, assigning a value to it "overwrites" the old value, so yes, it is literally lost, because variable values can change at any time.
When you work with objects, for example, let's say you have the class
Auto
:And you assign a new instance to it:
You have a new car placed in memory, if we do the following:
The new variable
OtroToyota
points to the reference of the new instance that we created earlier, which means that when you change a value in any of the instances, this value is changed in all the references you have to that object, example:So yes, your concept is true up to the point that you target the instance defined with the keyword
new
. If you assignnull
to one of the 2, the other (AND all other pointers to that instance) will be affected.See the following implementation as an example:
So your finally summarized answer is "Yes", but no "copies" of instances are kept in pointers (Or so I understand) .