Clarifying some relationships between types, upcasting, and classes/interfaces

53 views Asked by At

Everything occurs in Java. I'm not sure to what extent the programming language affects my questions, and I would be interested to know.

Suppose I have a class Animal, and a subclass which extends Animal called Dog. My understanding is that writing

Animal dog1 = new Dog();

constructs an object Dog called dog1 of type Animal. If I now write

Dog dog2 = new Dog();

then this constructs an object Dog called dog2 of type Dog. Suppose now I upcast the type of dog2 to type Animal. Then I lose access to all methods in Dog which are not overrides of methods in methods in Animal (otherwise, the corresponding methods in Dog are called).

Now suppose I add interfaces into the above story. From what I've read, every object has exactly one class-type (e.g. in the above, dog1 is type Animal, and dog2 is type Dog pre-upcast). However, objects have (not can have, but have) multiple interface-types, one for each interface the class implements. Suppose the class Dog implements the interface isCute, and suppose the class Animal implements the interface isLiving. In this case, I have the following questions.

  1. Is the type of dog1 both Animal and isLiving?
  2. Is the type of dog2 both Dog and isCute? Or is the type of dog2 Dog, isCute, and isLiving?
  3. If I upcast dog2 to Animal, is the type of dog2 Animal and isLiving?

I have tried searching, but I don't see answers covering discussing this relationship in too much depth. Most answers resort to "don't use upcasting" which is not an answer I am looking for.

1

There are 1 answers

0
Mr. Brown On

I’ll update this with corrections if needed. Thanks to the comments, one big clarification is the difference between object types and reference types. As far as I can tell, objects have as many types as there are classes they (maybe implicitly) extend and instances they implement. There is at most one reference type, and this is always a class-type (is this true?)

So to answer my original question: all instances have the same object type, namely Animal, Dog, isCute and isLiving, among others.

  1. The reference type is Animal.
  2. The reference type is Dog.
  3. The reference type is Animal.