Home   Cover Cover Cover Cover
 

Compatibility between classes

Question: Why is the relationship between a subclass and its superclass called an "is" relationship? Why can a subclass object (e.g. of type Dog) be assigned to a superclass variable (e.g. of type Animal) but not the other way around?

Answer: The relationship between a subclass and its superclass is called "is" relationship, because every object of the subclass is a special instance of the superclass. It has the same fields and methods as an object of the superclass and can therefore be used in the same way.

Since Dog is a special kind of Animal, a Dog object can be assigned to an Animal variable. As a result, the Animal variable references the Dog object. However, the Animal variable can only be used to access fields and methods that were already declared in Animal.

If an Animal object were assigned to a Dog variable the is a relation would be violated. Not every Animal is a Dog. The Dog variable would reference an Animal object, which does not contain all the fields of the Dog class. Some accesses to fields of the Dog variable would then go into the void.