MCAWALA

Java Vertical Menu

🧬 Java Inheritance – आसान भाषा में

🔰 What is Inheritance in Java?

Inheritance Java की Object-Oriented Programming (OOP) की एक खास feature है। इससे एक class दूसरी class की properties और methods को reuse कर सकती है।

👨‍👦 Real-Life Example:

जैसे बच्चा अपने माता-पिता से कुछ गुणों को विरासत में लेता है, वैसे ही Java में एक class दूसरी class से features inherit कर सकती है।

📘 Syntax of Inheritance:

class Parent {
    void showMessage() {
        System.out.println("I am Parent Class");
    }
}

class Child extends Parent {
    void display() {
        System.out.println("I am Child Class");
    }
}

public class Main {
    public static void main(String[] args) {
        Child obj = new Child();
        obj.showMessage(); // Inherited method
        obj.display();     // Child's method
    }
}

🔎 Keywords Used:

  • extends – subclass को superclass से जोड़ने के लिए
  • super – parent class के constructor या method को access करने के लिए

🧱 Types of Inheritance in Java:

Type Description
Single Inheritance एक class दूसरी class से inherit करती है
Multilevel Inheritance एक class दूसरी class से, और वो class एक और class से inherit करती है
Hierarchical Inheritance एक class से कई subclasses inherit करते हैं
Multiple Inheritance Java में class से multiple inheritance सीधे possible नहीं है, लेकिन interfaces से हो सकता है

🧪 Example – Multilevel Inheritance

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

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

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

public class Test {
    public static void main(String[] args) {
        Puppy p = new Puppy();
        p.eat();   // from Animal
        p.bark();  // from Dog
        p.weep();  // from Puppy
    }
}

🎯 Benefits of Inheritance:

  • ✅ Code Reusability
  • ✅ कम कोड, ज्यादा clarity
  • ✅ Easy to manage and extend
  • ✅ Structured और efficient programming

❗ Important Notes:

  • Java में class-based multiple inheritance allowed नहीं है
  • Interfaces का इस्तेमाल करके multiple inheritance achieve किया जा सकता है

🔚 Conclusion:

Inheritance एक powerful concept है जो Java में कोड को छोटा, reusable और maintainable बनाता है। यह OOPs की base pillars में से एक है।