What is inheritance in OOP (Java)?

Inheritance is one of the important pillars of Object-Oriented Programming.

Let’s say there is a child named Tom and his father, Mike, owns a car that he bought with his savings. As per inheritance, this car will belong to Tom after his father. Now, Tom doesn’t have to save his own money to buy a car – he already has one.

Inheritance in code is a mechanism through which one class (Tom) can inherit the members (assets) of the parent class.

The example below shows an animal class with all its properties (fields) and behaviors (method):

class Animal{
public void eat(){
//implementation here
}
public void sleep(){
//implementation here
}
}

There is also an elephant class and that has its own properties and behaviors including the eat() and sleep() methods. If these methods are not inherited, they have to be re-written.

public class Elephant{
int weight;
int age;
public int getAge(){}
public int getWeight(){}
public void printName(){}
public void eat(){}
public void sleep(){}
}

Through inheritance, we can reuse the eat() and sleep() methods of the animal class rather than re-writing the same code again. Let’s say that the elephant class inherits the animal class. The keyword extends will be used for that purpose.

public class Elephant extends Animal{
/* By extending this class inherits all the properties and behaviors which in this case include the eat() and sleep() methods*/
int weight;
int age;
public int getAge(){}
public int getWeight(){}
public void printName(){}
//Inherits the eat() method
//Inherits the sleep() method
}

As per our first example, Tom didn’t have to buy another car, as he can use the car he inherited from his dad.

The key thing here is reusability. When we use inheritance it allows us to reuse the existing code.

The terminologies for a class inheriting another class are:

  • Child class
  • Sub-class
  • Derived class

The terminologies for a class being inherited are:

  • Parent class
  • Super class
  • Base class

Note: We will use the extend keyword for inheritance.

Multi-level inheritance

In inheritance, just as in real life, we have a Grandparent -> Parent -> Child hierarchy. So, when the child inherits a parent class it also acts as a parent for another child class.

Class A {}
Class B extends A {}
Class C extends B {}

Here, class B is a child class that inherits from class A and acts as a parent for class C.

Single level inheritance

There is only one level of inheritance in single-level inheritance:

Class A {}
Class B extends A {}

Hierarchical Inheritance

In hierarchical inheritance, a class acts as a parent with multiple children.

Class A {}
Class B extends A {}// Child 1
Class C extends A {}// Child 2
Class D extends A {}// Child 3

Members in the parent class that have access to the Private modifier are not inherited.

Although you cannot inherit multiple classes in Java, you can in C++.

Free Resources

Attributions:
  1. undefined by undefined