Explain about Inheritance

In Java, inheritance allows a class (called the subclass or child class) to inherit fields and methods from another class (called the superclass or parent class). This promotes code reuse and establishes a natural hierarchy between classes.

Java uses the keyword extends to achieve inheritance.

🧩 Types of Inheritance in Java

  1. Single Inheritance
    • A child class inherits from one parent class.
  2. Multilevel Inheritance
    • A class inherits from a child class, which in turn inherits from another class.
  3. Hierarchical Inheritance
    • Multiple classes inherit from the same parent class.
  4. Hybrid Inheritance (Not supported directly in Java)
    • Combination of two or more types of inheritance; Java avoids this using interfaces.
  5. Multiple Inheritance (via Interfaces only)
  • A class implements multiple interfaces to achieve multiple inheritance.

✨ Examples

✅ 1. Single Inheritance

class Animal {
    void sound() {
        System.out.println("Animal makes a sound");
    }
}

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

public class Main {
    public static void main(String[] args) {
        Dog myDog = new Dog();
        myDog.sound(); // Inherited method
        myDog.bark();  // Child's own method
    }
}

✅ 2. Multilevel Inheritance

class Animal {
    void sound() {
        System.out.println("Animal sound");
    }
}

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

class Puppy extends Dog {
    void weep() {
        System.out.println("Puppy weeps");
    }
}

public class Main {
    public static void main(String[] args) {
        Puppy pup = new Puppy();
        pup.sound();
        pup.bark();
        pup.weep();
    }
}

✅ 3. Hierarchical Inheritance

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

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

class Cat extends Animal {
    void meow() {
        System.out.println("Cat meows");
    }
}

public class Main {
    public static void main(String[] args) {
        Dog d = new Dog();
        Cat c = new Cat();
        d.eat();
        d.bark();
        c.eat();
        c.meow();
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *