Pages

SPONSORED

What do you mean by Inheritance?

Inheritance is a process through which one object can inherit the characteristics of another object. This is similar to the parent-child relationship in real time scenario where a child can inherit the characteristics of parent.

Inheritence  helps in setting up relationships among objects and can help in reusing of code. Implementations of the parent can be simply inherited by the child. The child need not re-implement the functionality unless any change in behaviour is expected.This also impleves maintainability by avoiding duplication of code and hence reduces defects as well as development time. This in turn can improve code quality.

In inheritance, objects are defined by classes. The existing class is also called as– super class, parent class, base class and ancestral class. The inherited class is called as – sub class, child class, heir class or derived class.

 
Inheritence can be depicted by a simpe example -
To represent different kinds of geometric shapes, such as circles or rectangles programmatically we can use inheritance. We can create separate classes for each shape, but these different kinds of shapes share a number of things in common. We can define a type called "Shapes" to represent any of these different kinds of figures (circles or rectangles). We could then say that circles and rectangles are a kind of figure. A given type includes all of the record components specific to it, plus all the record components of its ancestors, so a square has all the information a rectangle would.

We'll also need to define some operations on these types, such as "Draw", "Area", and "Perimeter". Each calculated in a different way for each of the shape. Pictorial representation of this example is shown below.



Inheritance Example
 
 
We have seen how and when to use inheritence. We have also discussed its advantages. This does not mean that we implement inheritence in all scenarios. Do not use inheritence just for the sake of reuse. Avoid using it if there is no sub type relationship. Overuse of implementation inheritance can break all the subclasses, if the superclass is modified. Use composition for code reuse in such cases.

Quality of code can be achieved when the developer is smart enough to decide on the feature to put into use from OOP.

No comments:

Post a Comment