Inheritance

Inheritance is a fundamental concept in Java that allows one class to acquire the properties and behaviors of another class. It promotes code reusability and helps in building a hierarchical classification.

In Java, inheritance is implemented using the extends keyword.

Why Use Inheritance?

  • Code Reusability – Avoids redundant code by using already defined functionality.
  • Maintainability – Easier to manage and update the code.
  • Extensibility – Enhances the existing functionality without modifying the base class.
  • Polymorphism Support – Enables method overriding, making the code more flexible.

Syntax

Here, Child class inherits the show() method from the Parent class.

Types of Inheritance

Single Inheritance

A subclass inherits from a single parent class.

Example: A Dog class inherits properties from an Animal class.

Multilevel Inheritance

A class inherits from another class, which itself is inherited from another class.

Example: Grandparent → Parent → Child

Hierarchical Inheritance

Multiple child classes inherit from a single parent class.

Example: A Car and Bike class both inherit from Vehicle.

Why Java Doesn’t Support Multiple Inheritance?

Java does not support multiple inheritance using classes to avoid ambiguity problems (Diamond Problem).

Diamond Problem Example:

Java supports multiple inheritance using interfaces instead of classes.