Introduction

Inheritance is a fundamental concept in Object-Oriented Programming (OOP) that allows a new class to inherit properties and behaviors (methods) from an existing class. The existing class is known as the parent class or superclass, and the new class is known as the child class or subclass.

Key Points of Inheritance -

  1. Reusability: Inheritance promotes code reusability by allowing new classes to reuse the code of existing classes.
  2. Hierarchical Relationships: Inheritance creates a hierarchical classification, where a more general class shares attributes and behaviors with more specialized classes.
  3. Polymorphism: Through inheritance, a child class can be treated as an instance of its parent class, which supports polymorphism.

Types of Inheritance -

  1. Single Inheritance: A child class inherits from only one parent class.
  2. Multilevel Inheritance: A child class inherits from a parent class, which in turn inherits from another parent class.
  3. Hierarchical Inheritance: Multiple child classes inherit from a single parent class.
  4. Multiple Inheritance : A child class inherits from more than one parent class. (Not directly supported in Java, but can be achieved using interfaces whenever a class implements that interface it’s the class’s responsibility to implement it.)

    Diamond Problem Inheritance

    ⚠ Switch to EXCALIDRAW VIEW in the MORE OPTIONS menu of this document. ⚠ You can decompress Drawing data with the command palette: ‘Decompress current Excalidraw file’. For more info check in plugin settings under ‘Saving’

    Excalidraw Data

    Text Elements

    Class A

    Class B

    Class C

    Class C extends A, B { }

    Class B { getEngine(); }

    Class A {

    getEngine();

    }

    C obj = new C(); obj.getEngine(); Not knows which getEngine() method inherit.

    Link to original