2.8 Type Compatibility2.7 Code Sharing2 Java with Caffeine2.9 Object Assignments

2.8 Type Compatibility

Sharing code among multiple classes is only one aspect of inheritance. Another one that is even more important is that a subclass is compatible with the superclass. As a general rule:

Every program that is able to work with objects of the superclass can automatically also work with objects of the subclass.

Let us illustrate the consequences of this rule by our example of the Internet shop. We can write a program that works with objects of type Article, i.e., it can place them into a shopping cart, print the contents of a shopping cart, and compute the total price of an order without making a difference between the various kinds of article.

Later on, we may implement various concrete articles by deriving subclasses of Article, e.g., Book, CD, or Video. Therefore objects of these classes are special variants of articles, and the program can immediately work with them (place them into the shopping cart, extract their price and so on) as if they had existed when the program was written. The program need not be modified to work with the new kinds of articles.

Between subclass and superclass there is a  is-relationship which can be summarized by the following rule:

Every object of a subclass is also an object of the superclass.

This rule (which implies the previously stated rule), can be illustrated by a  set diagram as shown in the following diagram:


The

The Is-Relationship between Subclasses and Superclasses
 


The set of all objects of type Article has as subsets the set of all objects of type Book and the set of all objects of type CD. In other words, every object of type Book or of type CD is also an object of type Article.


© Wolfgang Schreiner; February 3, 2005

2.8 Type Compatibility2.7 Code Sharing2 Java with Caffeine2.9 Object Assignments