Java Tutorial 2: Introduction to object oriented programming Inheritance

In our previous tutorial i.e. A programmer's Diary: Java Tutorial 1: Introduction to object oriented programming we touched the concept of objects and classes. In this tutorial we will try and grab the concept of inheritance. Ok so we established that classes are blueprints. But sometimes 1 blueprints is built on the foundation of the other blueprint. In this case we say that blueprint number 2 is derived from blueprint number 1. It has same features has blueprint number one and plus its own features.




Talking in layman terms a car is an entity on its own. A special sports car is also car but it has some additional features like engine power , nitro boosters, etc. A taxi is also a car but it has meter installed in it. Similarly a police car has a siren in it.
So we can say sports car, taxi, police car are all inherited from car each having features of a normal car but with some additional features of their own.



Similarly in programming classes can be inherited and derived. According to http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html


A class that is derived from another class is called a subclass (also a derived classextended class, or child class). The class from which the subclass is derived is called a superclass (also a base class or a parent class).


Advantages of using Inheritance

  • Code reuse: When features are derived you don't have to code the same features again and again in different classes. For example we can program accelerate and decelerate in the class CAR. Then in classes police car, taxi, etc. we dont have to program it again. 
  • Easier changes: When we have common code , a change in functionality in base class will be reflected in all the child class without any significant copy paste effort. This makes the process of introducing changes easier. Else we would have to make changes in all four classes(CAR,  police car, taxi, sports car). And by mistake if miss making changes even in one, it would lead to inconsistencies. 
  • Extensibility:  With inheritance we can add  new functionality by plugging in new features in extended without changing existing classes as long the new plug-in classes extend given base classes.  

0 comments: