Reputation: 39
Lets say I have a Car Class and I create a reference variable for this Car Class.
Car car = new Car()
- Fairly Straightforward.
I edit the properties of that car by calling: car.setColor("Red"), and car.setPrice(2500).
Now, let's say I want to create a new Car Object, do I have to create a new reference variable like this: Car car2= new Car();
or can I just simply use the original reference variable for the new car?
Upvotes: 2
Views: 72
Reputation:
Expanding on Sweeper's answer:
If we instead do this:
Car car1 = new Car();
car1.setColor("Red");
car1.setPrice(2500);
Car car2 = car1;
car2.setColor("Blue");
car2.setPrice(3000);
Then both car1 and car2 will have a color of blue and a price of 3000, because they are pointed at the same object. If we then reassign car1:
car1 = new Car();
car1.setColor("Green");
car1.setPrice(0);
car1 would have a color of green and a price of 0, but car2 would still have a color of blue and a price of 3000, because it is still referencing the original object created for car1.
Upvotes: 2
Reputation: 271135
Short answer: It's up to you.
Long answer: You can use either method. If you create a new car, the previous car that you created will not be affected, because different objects are completely independent. Let's say
Car car1 = new Car();
car1.setColor("Red");
car1.setPrice(2500);
Car car2 = new Car();
car2.setColor("Blue");
car2.setPrice(3000);
Now car1
and car2
have different colours and prices. If you change the values of car1
, car2
will not be affected.
Alternatively, you reuse car1
:
Car car1 = new Car();
car1.setColor("Red");
car1.setPrice(2500);
car1 = new Car(); //You created the new car here
car1.setColor("Blue");
car1.setPrice(3000);
After this code, the original content of car1
is lost*. This can be used if you think car1
is not useful anymore and its contents can be discarded.
*Note: the object of car1
is still in memory. But it is inaccessible.
Upvotes: 3
Reputation: 77177
You can certainly reuse your first car
variable, and this is common in some cases (such as loops). Keep in mind that the original variable's reference will be replaced, so unless you've stored a reference to the object somewhere else (such as in a collection or a field on another object), the object will be garbage collected.
Upvotes: 0
Reputation: 962
Object is nothing but the temporary buffer created in the Heap.
Whenever you create a new object, a new buffer(or space) is provided in the heap.
Upvotes: 0