Inheritance in Java OOPs with Example

What is Inheritance?

Inheritance is a mechanism in which one class acquires the property of another class. For example, a child inherits the traits of his/her parents. With inheritance, we can reuse the fields and methods of the existing class. Hence, inheritance facilitates Reusability and is an important concept of OOPs.

In this tutorial, you will learn-

Types of Inheritance

There are Various types of inheritance in Java:

Single Inheritance:

In Single Inheritance one class extends another class (one class only).

Types of Inheritance
Single Inheritance

In above diagram, Class B extends only Class A. Class A is a super class and Class B is a Sub-class.

Multiple Inheritance:

In Multiple Inheritance, one class extending more than one class. Java does not support multiple inheritance.

Types of Inheritance
Multiple Inheritance

As per above diagram, Class C extends Class A and Class B both.

Multilevel Inheritance:

In Multilevel Inheritance, one class can inherit from a derived class. Hence, the derived class becomes the base class for the new class.

Types of Inheritance
Multilevel Inheritance

As per shown in diagram Class C is subclass of B and B is a of subclass Class A.

Hierarchical Inheritance:

In Hierarchical Inheritance, one class is inherited by many sub classes.

Types of Inheritance
Hierarchical Inheritance

As per above example, Class B, C, and D inherit the same class A.

Hybrid Inheritance:

Hybrid inheritance is a combination of Single and Multiple inheritance.

Types of Inheritance
Hybrid Inheritance

As per above example, all the public and protected members of Class A are inherited into Class D, first via Class B and secondly via Class C.

Note: Java doesn't support hybrid/Multiple inheritence

Inheritance In Java

JAVA INHERITANCE is a mechanism in which one class acquires the property of another class. In Java, when an "Is-A" relationship exists between two classes, we use Inheritance. The parent class is called a super class and the inherited class is called a subclass. The keyword extends is used by the sub class to inherit the features of super class.

Inheritance is important since it leads to the reusability of code.

Java Inheritance Syntax:

class subClass extends superClass  
{  
   //methods and fields  
}  

Java Inheritance Example

The super keyword is similar to "this" keyword.

The keyword super can be used to access any data member or methods of the parent class.

Super keyword can be used at variable, method and constructor level.

Syntax:

super.<method-name>();

Learn Inheritance in OOP’s with Example

Consider the same banking application from the previous example.

We are supposed to open two different account types, one for saving and another for checking (also known as current).

The functions are not required to be implemented individually. This is Inheritance in java. .

Java Inheritance & Polymorphism

Java Inheritance & Polymorphism

 

YOU MIGHT LIKE: