Inheritance

 

Inheritance is the property whereby one class extends another class by including additional methods and/or variables. The original class is called the superclass of the extending class, and the extending class is called the subclass of the class that is extended. Since a subclass contains all of the data and methods of the superclass plus additional resources, it is more specific; conversely, since the superclass lacks some of the resources defined in the subclass, it is more general or abstract, albeit less detailed, than its subclasses.

Much of the power of o-o programming comes form inheritance. It allows the programmer to define just once the properties several types of data have in common and then to define separately only the additional, distinguishing features for each specific type. Thus, for example, one can define a type, graph, that includes variables and methods associated with maintaining sets of nodes and links. One can then define tree, list, directed_graph, etc., by defining only the additional features that distinguish each subtype.

Superclass. Original class includes public and private variables as well as public and private methods. Extension. Extends the class on the left by defining two additional public methods, two private variables, and one private method.

 

Subclass. A subclass of the superclass includes both the variables and methods of the original class and those of the extension.

When viewed as a whole, the various classes related to one another through subclass - superclass relationships form a hierarchy, called the class hierarchy.

Class hierarchy. The classes related to one another through the subclass - superclass relationship form a hierarchy.

The current Java class hierarchy, as defined by Sun, can be browsed through the Java API.