Suppose we have the following code snippet:
Cat cat = new Cat(); // The Cat class extends Animal
ArrayList<Animal> animalList = new ArrayList<>();
animalList.add(cat);
cat is a reference of type Cat that points to an object of type Cat
animalList.get(0) is a reference of type Animal that points to the same object as the cat reference.
cat == animalList.get(0) will evaluate to true since they are both pointing to the same object.
However, one reference is of type Cat and the other of type Animal(position 0 in list), so am I wrong in saying that the references are not entirely equal, even though they point to the same memory location? Am I looking into the terminology too much?
This existing answer uses a nice analogy around houses, which describes references as "addresses", that allow you to find "houses" (those represent the instantiated objects).
If you extend that thinking, you could say that it's possible to print addresses on different cards. So these cards look different, but the address printed on them is always the same.
So yes, the compiler has a certain understanding of the references (or to be precise: **variables) being "different" (you can't invoke the Cat methods on an Animal reference). But at runtime, that part is completely gone. Then we are only comparing the "address" printed on the "cards".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With