Inheritance and Composition

From Studyplace

Jump to: navigation, search

As a general rule we look for ways to avoid duplicating code and functionality in programming. Composition and inheritance are two ways to achieve code reuse in object oriented programming. Composition allows us to build new classes from already existing classes. For example, if we are creating the object model of a personal computer we might construct our Computer class from other classes: HardDrive, DVDDrive, CPU, etc. Just as a real-world computer is built using component parts, our Computer object is composed of re-usable components. Our Java code might look like this:

public class Computer
{
    private CPU cpu;
    private HardDrive hardDrive;
    private DVDDrive dvdDrive;  
    //...
}

We may then go on to write a different program where we model mobile phones. Since our phones also have a CPU we are able to reuse the CPU class in our new program.

It is often said that composition represents a "has-a" relationship between two objects (i.e. a computer has a hard drive). Inheritance differs from composition in that it represents an "is-a" relationship. Inheritance operates through a hierarchical relationship of super-classes and sub-classes or parent and child classes. In Java we say that the sub-class extends the super-class: the sub-class has the complete set of functionality defined in the super-class and then extends it with its own functionality. To see an example of inheritance you can refer to the Employee Database example in the abstraction article. In this case SalariedEmployee extends the more abstract Person. The sub-class is always a super set of the super-class. We will see how this is very useful in the section on polymorphism.

It is a general aphorism that composition is preferred to inheritance, especially when either approach can be used to solve the problem. Composition leads to more stable and straightforward code. Inheritance can lead to weak encapsulation. A sub-class in an inheritance chain inherits the internal workings of the parent class. For this to work, the programmer must either a) know how that class works, reducing the abstraction offered by the parent class, or b) optimistically hope that the parent class will not change at any point in the future in a way that adversely affects the sub-class. Composition, on the other hand, offers a direct relation to the composing class. It relies on the public interface of the class in question, not its internal operation. Therefore abstraction is as week or strong as any other relationship between objects.

Personal tools