Inheritance in java with example

(Last Updated On: February 28, 2019)

Learn inheritance in Java with simple example and easy steps. Types of inheritance and advantage of using inheritance is explained.

Inheritance in Java

Inheritance is one of basic oops principles in java. In inheritance relationship, a class can access fields and methods of an existing class.

Existing class is known a as base class or parent class. The class who access the features i.e. fields and methods of base class is known as subclass, derived class or child class.

Child class use extends keyword to inherit feature of parent class e.g. class Son extends Father{}

 

Inheritance Example

Let’s consider an example,

A son wants to use his father’s home and car and he has his own mobile only. So, the son can access his father’s home and car.

So, Father is the parent class and Son is the child class.

Java Code:

Output:

Father’s Home
Father’s Car
Son’s mobile

 

Types of Inheritance in Java

Following types of inheritance are available in Java language.

Single Inheritance :

Single inheritance is just a parent and child class relationship. There should be one base class and one child class only. The java source code example for inheritance shown above is of single Inheritance.

Multilevel Inheritance

Multilevel inheritance java program example- In Multilevel inheritance, a class is derived from another class which is also derived from some another class … For example class C extends class B and class B extends class A then this type of inheritance is known as multilevel inheritance….Multilevel inheritance

Hierarchical Inheritance

When more than one classes inherit the same class is known as hierarchical inheritance…Hierarchical Inheritance in java.

Hybrid Inheritance

In hybrid inheritance, we use mixed of different types of inheritance relationship in java program. For example, we can mix multilevel and hierarchical inheritance etc…. Hybrid inheritance.

Multiple inheritance

Multiple inheritance in Java program can be implemented using interfaces not classes. Java does not support multiple inheritance using classes…Multiple inheritance.

 

Advantage of Inheritance

Main advantage of inheritance principle in java is RE- USABILITY. Meaning, use the existing class features already written by inheriting it in a new class.

Refresh…:

  • Parent class is also known as Base class / Super class
  • Child class is also known as Derived class /Sub class
  • Child class uses “extends” keyword to inherit a base class.
  • Child class cannot inherit private methods of parent.