Inheritance in Java is a mechanism where one class (child class) inherits the fields and methods of another class (parent class). It enables code reusability and establishes a parent-child relationship between classes.

Key Points:

  1. extends Keyword: Used to inherit a class.
  2. Access Control:
    • public and protected members of the parent class are accessible in the child class.
    • private members are not accessible but can be accessed through public/protected methods.
  3. Types:
    • Single Inheritance: One child, one parent.
    • Multilevel Inheritance: Child inherits from a parent, and that parent is also a child of another class.
    • Hierarchical Inheritance: Multiple classes inherit from a single parent class.

Java doesn’t support multiple inheritance with classes (to avoid ambiguity) but allows it with interfaces.

Example:

// Parent class
class Animal {
    String name;

    void eat() {
        System.out.println(name + " is eating.");
    }

    void sleep() {
        System.out.println(name + " is sleeping.");
    }
}

// Child class
class Dog extends Animal {
    void bark() {
        System.out.println(name + " is barking.");
    }
}

public class InheritanceExample {
    public static void main(String[] args) {
        // Creating an object of the child class
        Dog dog = new Dog();
        
        // Accessing parent class members
        dog.name = "Buddy"; // Inherited field
        dog.eat();          // Inherited method
        dog.sleep();        // Inherited method
        
        // Accessing child class method
        dog.bark();
    }
}

Output:

Buddy is eating.
Buddy is sleeping.
Buddy is barking.

Key Notes:

  1. Advantages: Reusability, modularity, and reduced redundancy.

  2. Overriding: A child class can provide its own implementation of a method from the parent class using the @Override annotation.

  3. Super Keyword: Used to call the parent class’s methods or constructor explicitly.