July 2002 Technical Tip An Introduction to Inheritance
Last month we discussed Object Think. First introduced by Coad and Nicola in 1993, Object Think represents a very natural way to think of objects, and from that process we can design the classes which will be used to create those objects. With object think, we let the object talk about itself. Specifically, the object says "This is what I know " and "This is what I know how to do " That which I know (or need to know) will become attributes, and that which I know how to do (or need to know how to do) will become behaviors.
This month we introduce a critical component of object-oriented programming inheritance. In simplest terms, inheritance is an "is a" relationship. In Java, the keyword extends indicates an inheritance relationship. The class which is being extended is the superclass, and the class which is doing the extending is the subclass. Every instance of the subclass "is a" instance of the superclass. We will use a simple example to illustrate this concept.
Consider the following sets of numbers:
We can illustrate this with a Venn diagram as follows:
In Java we say natural numbers extends whole numbers, and whole numbers extends integers. It is impossible in the limited space available to give this topic the coverage it deserves. The sample programs which follow will work, and the output is shown. Significant functionality is missing (such as getters, setters, error checking and the ability to add, subtract, multiply and divide!) but this should be sufficient to introduce the notion of inheritance to the Java novice.
This tip is presented with a working application. You'll find that our classes like our tips are loaded with examples, making for a more enjoyable and productive learning experience. We hope you will consider Caliber Data Training for your training and development needs!