Thought Sharing

Tuesday, June 11, 2013

Containership Vs. Inheritance

Containership is the concept of having one or more objects of one or more classes as data members of another class. Containership is the capacity of a class to contain objects of different classes as member’s data. For example, the class A could contain an object of class B as a member. Here, all public functions defined in B can be used in the class A. The Class A becomes the container, while the class B becomes the contained class. In OOP, Containership represents one ‘has – a’ relation. It is important to note that, although the container has access to carry out all public methods of the contained class, it is not able to change or provide additional functionality.

Inheritance is the capacity for a class to inherit properties and behavior of a parental class by spreading it. Inheritance principally provides code reuse by allowing extending properties and behavior of an existing class by a newly defined class. If the class A is created from Class B, therefore the class B is parent class and the class A is called the child class (or derived class/sub class). The behavior of parent class can be overridden by derived class i.e. a derive class can modify the functions of parent class in it.

Difference between Containership and Inheritance:
If a class is extended, it inherits all public and protected properties/ behaviours and these behaviours can be overridden by the subclass. But if a class is contained in other one, the container does not get the capacity to change or add behavior to the contained class i.e. container. In Inheritance, the behavior of parent class can be overridden by derived class i.e. a derive class can modify the functions of parent class in it.

Inheritance represents ‘is -a ‘relationship in OOP, while Containership represents a’ has -a’ relationship.