Friday, September 7, 2007

Hierarchy

In computer science's object-oriented programming, the mapped relationships of sub- and superclasses is known as a hierarchy. This can be visualized as an upside-down tree (or perhaps a pyramid), the top of which is known as the root.

The issue is more complicated with languages that support multiple inheritance, where hierarchy can be any directed acyclic graph.

Aggregation or Composition relationships in object-oriented design also form a hierarchy, composition hierarchy.

In object-oriented programming, a class is a template that defines the state and behavior common to objects of a certain kind. A class can be defined in terms of other classes. For example, a truck and a racing car are both examples of a car. Another example is a letter and a digit being both a single character that can be drawn on the screen.

In the latter example, the following terminology is used:


  • The letter class is a subclass of the character class; (alternative names: child class and derived class)

  • The character class is immediate superclass (or parent class) of the letter class;

  • The letter class extends the character class.
The third formulation expresses that a subclass inherits state (instance variables) and behavior (methods) from its superclass(es). Letters and digits share the state (name, font, size, position) and behavior (draw, resize, ...) defined for single characters.

The purpose of a subclass is to extend existing state and behavior: a letter has a case (upper and lower case, say stored in the instance variable letterCase) and methods for changing the case (toUpperCase, toLowerCase) in addition to the state that it already has as a character.

However, a digit does not have a case, so the methods toUpperCase, toLowerCase do not belong on the common level of the Character class. There are methods that are special to the digit class. For instance, a digit may be constructed from an integer value between 0 and 9, and conversely, the integer value of a digit may be the result of say the intValue method.

In graphical terms, the above character example may look as follows:



The classes form a class hierarchy, or inheritance tree, which can be as deep as needed. For example, the letter class can have on its turn the subclasses vowel and consonant.




When a message is sent to an object, it is passed up the inheritance tree starting from the class of the receiving object until a definition is found for the method. This process is called upcasting. For instance, the method toString() is defined in the Object class. So every class automatically has this method.

In graphical terms, the inheritance tree and the message handling may look as follows:



A hierarchy is useful if there are several classes which are fundamentally similar to each other. In C++, a "base class" is a synonym for superclass and"derived class" is a synonym for subclass.


No comments: