Cover Data Structures and Algorithms with Object-Oriented Design Patterns in Java
next up previous contents index

Derivation and Inheritance

This section reviews the concept of a derived class. Derived classes are an extremely useful feature of Java because they allow the programmer to define new classes by extending existing classes. By using derived classes, the programmer can exploit the commonalities that exist among the classes in a program. Different classes can share values, operations, and interfaces.

Derivation  is the definition of a new class by extending an existing class. The new class is called the derived class  and the existing class from which it is derived is called the base class . In Java there can be only one base class (single inheritance  ).

Consider the Person class defined in Program gif and the Parent class defined in Program gif. Because parents are people too, the Parent class is derived from the Person class. Derivation in Java is indicated using the keyword extends.

   program56619
Program: Person class.

   program56630
Program: Parent class.

A derived class inherits  all the members of its base class. That is, the derived class contains all the fields contained in the base class and the derived class supports all the same operations provided by the base class. For example, consider the following variable declarations:

Person p = new Person ();
Parent q = new Parent ();
Since p is a Person, it has the fields name and sex and method toString. Furthermore, since Parent is derived from Person, then the object q also has the fields name and sex and method toString.

A derived class can extend the base class in several ways: New fields can be defined, new methods can be defined, and existing methods can be overridden . For example, the Parent class adds the field children and the method getChild.

If a method is defined in a derived class that has exactly the same signature (name and types of arguments) as a method in a base class, the method in the derived class overrides  the one in the base class. For example, the toString method in the Parent class overrides the toString method in the Person class. Therefore, p.toString() invokes Person.toString, whereas q.toString(...) invokes Parent.toString.

An instance of a derived class can be used anywhere in a program where an instance of the base class may be used. For example, this means that a Parent may be passed as an actual parameter to a method in which the formal parameter is a Person.

It is also possible to assign a derived class object to a base class variable like this:

Person p = new Parent ();
However, having done so, it is not possible to call p.Child(...), because p is a Person and a Person is not necessarily a Parent.




next up previous contents index

Bruno Copyright © 1998 by Bruno R. Preiss, P.Eng. All rights reserved.