2.7 Code Sharing2.6 Constructors in Derived Classes2 Java with Caffeine2.8 Type Compatibility

2.7 Code Sharing

What are the advantages of inheritance? One aspect that has been illustrated above is the reduction in the amount of code that has to be written. A subclass can inherit fields and methods from a superclass without declaring it locally. This aspect is especially important if there may be multiple subclasses that inherit from the same superclass. Rather than defining the common fields and method in each subclass, they are defined once and for all in the superclass. One should therefore obey the following strategy:

Whenever there are two or more classes that share common functionality, this functionality should be put in a separate superclass from which the other classes are derived by inheritance.

In this way, code may be shared among multiple classes, i.e., the duplication of code can be avoided.


© Wolfgang Schreiner; February 3, 2005

2.7 Code Sharing2.6 Constructors in Derived Classes2 Java with Caffeine2.8 Type Compatibility