0
0
Javaprogramming~5 mins

Why inheritance is used in Java

Choose your learning style9 modes available
Introduction

Inheritance helps us reuse code and organize related things easily. It lets one class get features from another without rewriting them.

When you want to create a new class that is a type of an existing class.
When many classes share common features and you want to keep those features in one place.
When you want to add new features to an existing class without changing it.
When you want to make your code easier to maintain and understand.
When you want to model real-world relationships like a Dog is an Animal.
Syntax
Java
class ParentClass {
    // common features
}

class ChildClass extends ParentClass {
    // new or specialized features
}

The extends keyword shows that one class inherits from another.

The child class gets all the features of the parent class automatically.

Examples
Dog inherits from Animal, so Dog can eat and bark.
Java
class Animal {
    void eat() {
        System.out.println("Eating food");
    }
}

class Dog extends Animal {
    void bark() {
        System.out.println("Barking");
    }
}
Car inherits move() from Vehicle and adds honk().
Java
class Vehicle {
    void move() {
        System.out.println("Moving");
    }
}

class Car extends Vehicle {
    void honk() {
        System.out.println("Honking");
    }
}
Sample Program

This program shows a Dog object using both its own method and the inherited method from Animal.

Java
class Animal {
    void eat() {
        System.out.println("Eating food");
    }
}

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

public class Main {
    public static void main(String[] args) {
        Dog myDog = new Dog();
        myDog.eat();  // inherited method
        myDog.bark(); // own method
    }
}
OutputSuccess
Important Notes

Inheritance helps avoid repeating code in many classes.

Use inheritance only when there is a clear 'is-a' relationship.

Java supports single inheritance for classes, meaning one class can extend only one parent class.

Summary

Inheritance lets a class get features from another class.

It helps reuse code and organize related classes.

Use inheritance to model real-world relationships and add new features easily.