java - New Reference Variable Each Time I create an Object? -


lets have car class , create reference variable car class.

car car = new car()- straightforward.

i edit properties of car calling: car.setcolor("red"), , car.setprice(2500).

now, let's want create new car object, have create new reference variable this: car car2= new car(); or can use original reference variable new car?

short answer: it's you.

long answer: can use either method. if create new car, previous car created not affected, because different objects independent. let's

car car1 = new car(); car1.setcolor("red"); car1.setprice(2500); car car2 = new car(); car2.setcolor("blue"); car2.setprice(3000); 

now car1 , car2 have different colours , prices. if change values of car1, car2 not affected.

alternatively, reuse car1:

car car1 = new car(); car1.setcolor("red"); car1.setprice(2500); car1 = new car(); //you created new car here car1.setcolor("blue"); car1.setprice(3000); 

after code, original content of car1 lost*. can used if think car1 not useful anymore , contents can discarded.

*note: object of car1 still in memory. inaccessible.


Comments

Popular posts from this blog

sublimetext3 - what keyboard shortcut is to comment/uncomment for this script tag in sublime -

java - No use of nillable="0" in SOAP Webservice -

ubuntu - Laravel 5.2 quickstart guide gives Not Found Error -