Inheritance in Java

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • MyrinNew
    Senior Member
    • Feb 2024
    • 5175

    #1

    Inheritance in Java

    What is Inheritance?


    Inheritance in Java is a feature where one class (child) can use the properties and methods of another class (parent).
    • The class that is inherited from is called Parent / Superclass
    • The class that inherits is called Child / Subclass
    • Java uses the keyword extends to achieve inheritance.


    In short
    • Parent class → Superclass
    • Child class → Subclass
    • Keyword used → extends


    🧠 Real-World Idea


    Think like this
    • A Car is a Vehicle
    • A Dog is an Animal
    • A Student is a Person


    This “IS-A” relationship is exactly what inheritance represents.


    💻 Simple Code Example






    class Vehicle {
    void start() {
    System.out.println("Vehicle is starting");
    }
    }

    class Car extends Vehicle {
    void drive() {
    System.out.println("Car is driving");
    }

    public static void main(String[] args) {
    Car c = new Car();
    c.start(); // inherited
    c.drive(); // own method
    }
    }







    📌 Why Do We Need Inheritance?
    • Code reusability
    • Reduces duplicate code
    • Improves maintainability
    • Supports method overriding
    • Helps achieve runtime polymorphism


    📌 Types of Inheritance


    1️⃣ Single Inheritance


    One child → One parent









    class A {}
    class B extends A {}







    ✅ Advantages of Inheritance
    • Code reusability
    • Less duplication
    • Easy maintenance
    • Supports polymorphism
    • Clean structure


    ❌ Disadvantages of Inheritance
    • Tight coupling
    • Parent changes affect child
    • Complex hierarchy
    • Not always flexible




    More...
Working...