Once again, we need to be careful of the reference trap.
There are two ways to fall for this trap, it can happen by mishandling arrays and objects.
In this lesson, we're going to see how this trap occurs when mishandling objects.
A trap happens when many variables a reference to one object.
If I update the object through one variable, it's going to affect the other.
To avoid the trap, do not set class variables equal to each other.
Sound familiar?
I hope so.
I told you the same thing about array variables.
The see this inaction will add another variable in Nissan to.
And we'll set it equal to the Nissan object.
And for now, I'd like to remove the setas.
Then we're going to print the fields from Nissan to.
OK, nothing weird so far.
Now, what if I decide to paint the second Nissan yellow?
Run the code.
Oh, I meant the only update, the second Nisan, but now the first Nissan is yellow as well.
You fell into the trap.
When you set a variable equal to another, it copies the value inside.
In this case, what's inside is a reference and now both variables share a reference that points to
the same object.
If I update the object, the one variable, it's going to affect the other.
This is bad.
The state of a variable should not change because you updated another, the reference shop can make
your code dangerous and unpredictable.
The solution is to make a new object, don't be lazy is create a new object.
Inside your code set the variable Nissan to equal to a new object.
And after creating a new object called the constructor, by passing the four values that it needs to
update your fields.
All right, run your code.
And as I expect, all of the objects are independent of each other.
Instead of setting the variables equal to each other, we made a new object and now my mind is at peace.
I can take comfort knowing that each variable points to a unique object.
I don't have to worry about the state of one variable being affected by another.
This is a great solution, so we can update our table of traps.
Don't worry, it's all in your cheat sheet.
So far, we went over to reference drops in this video, we talked about the second trap do not set
object variables equal to each other.
This doesn't copy the object.
It copies the reference.
Instead, set your variable equal to a new object.
It's much better if a variable points to a unique object, then you don't have to worry about the state
of one variable being affected by another.