Inheritance is one of the key features of Object Oriented Programming ( OOP ). The main idea behind the Inheritance is Code Re-use. Inheritance allows a class to use the properties and methods of another class. In other words, the derived class inherits the states and behaviors from the base class. The derived class is also called subclass and the base class is also known as super-class.The derived class can add its own additional variables and methods. These additional variable and methods differentiates the derived class from the base class.

To understand this better lets assume we have an Vehicle Class. This vehicle class has 3 properties 1) Color 2) Number of wheels 3) Speed

This class code is well tested and working fine. Now we received a new requirement from business to add a new vehicle of type truck which also has a property cargo capacity. One option is to modify Vehicle Class and add a new property “Cargo Capacity” to vehicle class.This option will certainly work but this will not be most efficient option. The reason is

  1. Vehicle class is well tested and if we make any changes to it we may introduce some new bugs and needed to re-test and deployed.
  2. Property “Cargo Capacity” does not apply to all vehicle types, like Motor Bike does not require Cargo Capacity.

To address above issues its a good idea to Create a new classs “Truck” and inherit this from Vehicle class. When we do this Truck class has all the properties of Vehicle, in addition to this it also has new property “Cargo Space”. By doing this we are doing a code re-use and extending Vehicle Class.

Below is an simple e.g.

//Super Class
public class Vehicle   {
   String Color;
   int noOfWheels;
   int Speed;   

//Sub Class 
public class Truck  extends Vehicle  {
   int cargoSpace;   

3 thoughts on “Inheritance

Leave a Reply

Your email address will not be published. Required fields are marked *