Table of Contents

Inheritance in Java

Definition:

Inheritance is one of the fundamental concepts of Object-Oriented Programming (OOP) that allows a new class (subclass or derived class) to inherit properties and behaviors (fields and methods) from an existing class (superclass or base class). This promotes code reusability and establishes a natural hierarchy between classes.

Key Concepts:

Example:

class Animal {
    void eat() {
        System.out.println("This animal eats food.");
    }
}

class Dog extends Animal {
    void bark() {
        System.out.println("The dog barks.");
    }
}

public class Main {
    public static void main(String[] args) {
        Dog dog = new Dog();
        dog.eat(); // Inherited method
        dog.bark(); // Method of Dog class
    }
}

Output:

This animal eats food.
The dog barks.

In this example, Dog is a subclass that inherits the eat method from the Animal superclass.

Types of Inheritance:

1. Single Inheritance:

A class inherits from only one superclass.

Example:

class Animal {
    void eat() {
        System.out.println("This animal eats food.");
    }
}

class Dog extends Animal {
    void bark() {
        System.out.println("The dog barks.");
    }
}

2. Multilevel Inheritance:

A class inherits from a superclass, and another class inherits from that subclass, forming a chain.