Inheritance in Java

Introduction

Inheritance is considered as a main feature of OOP (Object Oriented Programming). It is a process which allows one class to take the properties of another class. When we create a new class and inherit from an existing class, we can reuse its method and fields in the new class.

Relationship in Java

Inheritance represents IS-A relationship, also called parent-child relationship. For example –

Square is a Shape


Triangle is a Shape

Here, Square and Triangle are subclasses and Shape is considered as a super or the parent class.

Inheritance in java

Super Class – An existing class whose properties are inherited is known as Super class or Parent class.

Sub Class – The new class which inherits the properties of a super class is known as Sub class or Child class.

Why we use Inheritance?

  • To override methods, if we need a specific method implementation for the child class.
  • To reuse the code, so we don’t need to write the same method in the child class. We can easily re-use it.
  • To save the time.

Syntax

extends keyword is used to inherit the properties of a super class through Inheritance.

Code example of Inheritance

Here, Teacher is a Super class and Programmer is Sub class.

It means that Programmer IS-A Teacher.

Having said that, Programmer object can access its own fields as well as those of the Teacher.

Types of Inheritance

  1. Single inheritance
  2. Multilevel Inheritance
  3. Hierarchical Inheritance
  4. Multiple Inheritance

Single inheritance

When a class inherits or is inherited by only one single class then it is known as Single Inheritance.

Single Inheritance

Multilevel Inheritance

In Multilevel Inheritance, a subclass B inherits from a super class A and then for the next subclass C, the derived subclass B becomes the super class.

Multi-level Inheritance

Hierarchical Inheritance

In Hierarchical Inheritance, more than one sub classes can inherit the same super class.

Hierarchical Inheritance

Why multiple Inheritance is not possible in java?

Multiple Inheritance

Firstly, Java doesn’t support multiple inheritance as a particular class can never extend more than one class

Secondly, what if Java would have supported multiple inheritance. If two parent classes use the same method name draw(), and a child class which extends both the parents makes a call to the method draw() through its reference, then it creates an ambiguity while compilation, and it becomes difficult for Java to decide which function should execute. So the below code throws compilation error as expected.

This is the reason why Multiple Inheritance is not possible in Java.

Receive our updates to your inbox

Get more stuff like this
in your inbox

Subscribe to our mailing list and get interesting stuff and updates to your email inbox.