Main Page

Previous Next

Using Existing Classes

Let's start by understanding the jargon. Defining a new class based on an existing class is called derivation. The new class, or derived class, is referred to as a direct subclass of the class from which it is derived. The original class is called a base class because it forms the base for the definition of the derived class. The original class is also referred to as a superclass of the derived class. You can also derive a new class from a derived class, which in turn was derived from some other derived class, and so on. This is illustrated in the following diagram:

Click To expand

This shows just three classes in a hierarchy, but there can be as many as you like.

Let's consider a more concrete example. We could define a class Dog that could represent a dog of any kind.

class Dog {
  // Members of the Dog class...
}

This might contain a data member identifying the name of a particular dog such as "Lassie" or "Poochy" and another data member to identify the breed, such as "Border Collie" or "Pyrenean Mountain Dog". From the Dog class, we could derive a Spaniel class that represented dogs that were spaniels:

class Spaniel extends Dog {
  // Members of the Spaniel class...
}

The extends keyword that we use here identifies that Dog is a base class for Spaniel, so an object of type Spaniel will have members that are inherited from the Dog class, in addition to the members of the Spaniel class that appear in its definition. The breed would be "spaniel" for all instances of the class Spaniel although in general the name for each spaniel would be different. The Spaniel class might have some additional data members that characterize the specifics of what it means to be a spaniel. We will see in a moment how we can arrange for the base class data members to be set appropriately.

A Spaniel object is a specialized instance of a Dog object. This reflects real life. A spaniel is obviously a dog and will have all the properties of a basic dog, but it has some unique characteristics of its own which distinguish it from all the dogs that are not spaniels. The inheritance mechanism that adds all the properties of the base class – Dog in this instance – to those in the derived class, is a good model for the real world. The members of the derived class define the properties that differentiate it from the base type, so when you derive one class from another, you can think of your derived class as a specification for objects that are specializations of the base class object.

Previous Next
JavaScript Editor Java Tutorials Free JavaScript Editor