| Home | Previous Lesson: Inheriting the Code Next Lesson: Multiple Inheritance |
Using this strategy, you can design class hierarchy to inherit just the interface by the derived classes, and not the code. You write the actual code in the derived class. By this, the derived class has the same interface (in other words, same function names and arguments) as the base class, but behave differently for the same method.
Consider the previous example, every data-entry-form class, i.e., master entry, transaction entry have some common functionality, saving the data entered by the user. Since all these classes have common functionality, you may want to define the method "Save" at the base class. However, the implementation of saving the data is different from form to form. For example, master entry form is saving the data to the master file, while transaction entry form has to check for existence of the information in the master file and also update the master file whenever it writes to the transaction file. Thus, individual form objects may exhibit different behaviors, but they all share the same interface and so can be treated as 'data-entry-form' objects.
In this situation, you can define a method "Save" at the base class with no code in it and write the actual code in the derived classes. To do this, you need to use polymorphism, which is explained later in this chapter.
A class hierarchy designed for interface sharing has most of its code in the derived classes (near the bottom of the hierarchy). The derived classes represent working versions of an abstract model defined by the class.
Some times, you may need to design a class hierarchy, which has to implement both code and interface inheritance. If you take the examples from both the topics, and combine them, i.e., some methods, and some interfaces are common. So, the final diagram would look like the one shown below:
| Home | Previous Lesson: Inheriting the Code Next Lesson: Multiple Inheritance |