0
0
JavaConceptBeginner · 3 min read

Single Inheritance in Java: Definition and Example

In Java, single inheritance means a class inherits properties and methods from only one parent class. It allows a new class to reuse code from a single existing class, making code easier to manage and extend.
⚙️

How It Works

Single inheritance in Java works like a family tree where a child inherits traits from one parent only. Imagine a child learning skills from just one parent, not multiple. Similarly, a class (child) inherits fields and methods from one other class (parent).

This means the child class can use or change the behavior of the parent class without rewriting code. It helps programmers build new classes based on existing ones, making development faster and code cleaner.

💻

Example

This example shows a Dog class inheriting from an Animal class. The Dog class gets the sound() method from Animal and adds its own method fetch().

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

class Dog extends Animal {
    void fetch() {
        System.out.println("Dog fetches the ball");
    }
}

public class Main {
    public static void main(String[] args) {
        Dog myDog = new Dog();
        myDog.sound();  // inherited method
        myDog.fetch();  // own method
    }
}
Output
Animal makes a sound Dog fetches the ball
🎯

When to Use

Use single inheritance when you want to create a new class that is a specialized version of an existing class. It is useful when there is a clear "is-a" relationship, like a Dog is an Animal.

For example, in a game, you might have a base class Character and create subclasses like Wizard or Warrior that inherit common features but add their own unique abilities.

Key Points

  • Single inheritance means one class inherits from one parent class only.
  • It promotes code reuse and cleaner design.
  • Child class can use or override parent class methods.
  • Helps model real-world "is-a" relationships.

Key Takeaways

Single inheritance allows a class to inherit from exactly one parent class in Java.
It helps reuse code and extend functionality without rewriting existing code.
Use it when there is a clear "is-a" relationship between classes.
Child classes can add new features or change inherited behavior.
It simplifies program structure and improves maintainability.