Next Previous Up Top


4 Class Relationships

4.3 Inheritance


4.3 Inheritance


There is another, very different, kind of relationship possible between classes, a relationship where one class is an extension of another class. This relationship is known as inheritance and, together with dynamic binding, is a key feature of object-oriented programming.

Inheritance allows a class to take on, or inherit, all the features of another class. This is often represented in a diagram like this:

The class being inherited from is known as the superclass, while the class that inherits is known as the subclass. The subclass inherits the variables and methods declared by the superclass, meaning that the subclass includes the superclass variables and methods as part of itself. In addition, the subclass can add new variables and methods. Also the subclass can redefine or override the implementation of an inherited method so as to be able to specialize it to the needs of the subclass. The subclass is an extension or specialization of the superclass.

We can talk about inheritance as the is-a relationship, as the subclass is everything the superclass is, plus some new bits. For example, if we have a class Vehicle, a subclass Car can be defined as an extension of Vehicle. We can then say that a Car is-a Vehicle; a Car is everything a Vehicle is along with a set of additional features.

In terms of objects, if an object is an instance of a subclass then the representation will contain all the variables declared by both the subclass and the class it inherits from. Further, any of the methods declared by either class can be called for objects of the subclass, provided they are public, of course.

Inheritance is subject to some fairly complex rules, some of which will be introduced briefly in the following sections and most of which will be described in more detail in Chapter 14: the description in the last paragraphs is intended just to give a generalization of the key idea. The moral is that inheritance is a powerful and important mechanism that the Java programmer needs to be confident in using.


Copyright 1997 Russel Winder and Graham Roberts

Last updated: 6 Oct 1997