Student: Professor I wrote a program and I don’t get why it’s running that way.
Prof: Great! That probably means there’s something good to learn. Let’s see it!
Student: I made two
Menu instances, but it seems like updating one updates the other:Student: I’m confused because I thought
discountInPlace would only update the lunch menu, not the dinner one. But when I show the arrays it seems like all the arrays updated.Prof: Very interesting! I think what’s happening here is there is only one array.
Student: Only one array?
Prof: That’s right. Let’s look at a memory diagram at the end:
Prof: So that one array is created and stored in
regular, and that same reference is used to initialize both lunch and dinner. Look at the two objects – they have different references but both of the pricesCents fields store the same array reference!Student: I see, that one reference is referred to by five different places!
Prof: Right, and the array updates change the elements on the heap, so then if we access those elements through any of the references, we see the updated values. This idea has a name: it is called aliasing, when different names in a program store the same reference. Aliasing makes it so updates through one reference are visible through all the others.
Student: OK, I think I got it!
Practice
This program creates two arrays. Which one is stored in each team’s
players field?red.players: blue.players: green.players: gold.players: After
main runs, how many of the four teams have "Zed" as their first player?