Is the explanation about the answer in Unit 7 Lesson 2 Level 5 correct? " the item1 object and the item2 object both refer to the same object in memory" My understanding is that item1 isn’t set as a copy of item2, so they are not aliases to each other. item1 calls the updatePrice() method to change item2’s instance variable, price, and this doesn’t make item1 and item2 to be aliases either. Do I understand the code correctly? I’ll appreciate your inputs. Thanks!
The explanation
When the
updatePrice()method is called withitem2as the argument, it is actually passing a reference to theitem2object. In Java, objects are passed by reference, which means that changes made to the object inside the method will affect the original object outside the method.In the
updatePrice()method, thepriceattribute of the item object passed as a parameter is updated to10.0. Since theitem1object and theitem2object both refer to the same object in memory, thepriceattribute ofitem2is also updated to10.0.Therefore, when
System.out.println(item2.price);is executed, it prints the updated price of [10.0]
is almost correct. item1 and item2 do not refer to the same object. The item in the updatePrice method is an alias for/reference to item2 since item2 was passed in as a parameter. So the second sentence in the second paragraph should read:
Since the
itemobject and theitem2object both refer to the same object in memory, thepriceattribute ofitem2is also updated to10.0.
It is a little strange to write updatePrice this way, rather than as a static method. I would also definitely have students call out that since the System.out.println call is in another class than Item, it should/would not have access to the price member of item2.
Yes, your explanation makes sense to me. Item and Item2 are aliases. I tested the code today, and Item1 holds the same value, 5.0, at the end of the program. Thanks a lot for the inputs Brian!
Thanks @zhu.xiaobo for posting to question. There is a wealth of knowledge on this forum.
@dahlem_brian - thank you for that detailed explanation. We all appreciate the help…
Sylvia