Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java object reference mechanisms

Tags:

java

object

I'm kind of stuck on the following question:

What two Java language mechanisms allow the type of an object reference variable to be "different" than the type of the object to which it refers? Give specific examples to illustrate. In what sense are they not different at all?

My current answer is that it is "implement" and "extend" right? And they are similar because they both will make a class that at least will posses all of the method signatures of the super class which can be actual, abstract, or an interface. Is this correct? Thanks in advance!

like image 447
Wang-Zhao-Liu Q Avatar asked Oct 06 '22 18:10

Wang-Zhao-Liu Q


1 Answers

That is more or less correct. The second part of your answer should talk about subtyping. In Java, it is not sufficient for objects to just have the same method signatures. There actually has to be a declared subtyping relationship (via extends / implements).

This is not mere pedantry. In some languages (but not Java), the mere existence of compatible method signatures is sufficient for type compatibility. This is called "duck typing".

like image 96
Stephen C Avatar answered Oct 10 '22 03:10

Stephen C