In the real world, inheritance has a very specific meaning which is applied to many different areas. We can inherit money from relatives and genes from our parents. The idea is that something is being passed to us from someone else. OO (object orientation), the same inheritance idea is used with classes. Consider the following two classes -

They both are very different things. A van is much larger than a car, has more storage space and tends to be driven very recklessly on the M25! But clearly they both have very similar operations. They both accelerate and brake in very similar ways. We can take these similarities and place them into a new class called RoadVehicles . This new class will contain all of the similar methods and fields of Car and Van.

Car and Van now inherit from class RoadVehicles. They no longer define the methods themselves, but get them from class RoadVehicles. RoadVehicles is said to be the superclass of both Car and Van. Whilst Car and Van are subclasses of RoadVehicles.

 

Let’s look at a concrete example in Java. Consider a company who have to calculate tax payable for its employees. This has to be worked out for Payslips and for the employees records. Let’s say we have the following two classes.

 

class Payslip{

public int calculateTax(int amountEarned){
}

 

public void printPaySlip(){
}

}

 

class EmployeeRecords{
public int calculateTax(int amountEarned){
}

Public void storeRecord(){

}

}

 

They both have the method calculateTax, so we could create a superclass called TaxCalculator.

 

class TaxCalculator{

Public int calculateTax(int amountEarned){
// code would go here to work out tax

}

}

 

Finally we must tell Payslip and EmpolyeeRecords to inherit from TaxCalcualtor.

 

class Payslip extends TaxCalculator{

public void printPaySlip(){
}

 

}

 

class EmployeeRecords extends TaxCalculator{
Public void storeRecord(){

}

}