CSA 7.2.5 Check for Understanding

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 with item2 as the argument, it is actually passing a reference to the item2 object. 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, the price attribute of the item object passed as a parameter is updated to 10.0. Since the item1 object and the item2 object both refer to the same object in memory, the price attribute of item2 is also updated to 10.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 item object and the item2 object both refer to the same object in memory, the price attribute of item2 is also updated to 10.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.

2 Likes

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!

1 Like

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

1 Like