DEV Community

Mohammed mhanna
Mohammed mhanna

Posted on

🧬 Understanding Inheritance in Java

Inheritance is one of the four pillars of Object-Oriented Programming (OOP) in Java — and it’s a game changer when it comes to code reuse, structure, and scalability.

In this post, we’ll break down what inheritance is, why it matters, how it works in Java, and best practices you should follow when using it.


1️⃣ What is Inheritance?

Inheritance is the mechanism that allows one class to acquire the properties and behaviors of another.

In simple words:

One class (child) can inherit the fields and methods of another class (parent).


This helps reduce code duplication and promotes reusability.

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

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

public class Main {
    public static void main(String[] args) {
        Dog dog = new Dog();
        dog.eat();  // inherited from Animal
        dog.bark(); // defined in Dog
    }
}
Enter fullscreen mode Exit fullscreen mode

Output:

This animal eats food.
The dog barks.
Enter fullscreen mode Exit fullscreen mode

2️⃣ Why Do We Need Inheritance?

✨ Main benefits:

Code Reuse: Common functionality lives in the parent class.

Organization: Related classes share a logical hierarchy.

Scalability: Easy to extend existing functionality without rewriting code.

Polymorphism: Enables flexible and dynamic method behavior at runtime.

Example:
A Bird and a Fish both extend Animal — they share some traits but also have their own unique ones.


3️⃣ How Inheritance Works in Java ⚙️

Java uses the keyword extends for class inheritance and implements for interfaces.

class Parent { ... }
class Child extends Parent { ... }

Enter fullscreen mode Exit fullscreen mode

💡 By default, every class in Java implicitly extends Object, the root of the class hierarchy.


4️⃣ The Different Types of Inheritance in Java 🧩

  1. Single Inheritance: One class inherits from another.
class A { }
class B extends A { }

Enter fullscreen mode Exit fullscreen mode
  1. Multilevel Inheritance: A class inherits from a class that already inherits another.
class A { }
class B extends A { }
class C extends B { }
Enter fullscreen mode Exit fullscreen mode
  1. Hierarchical Inheritance: Multiple classes inherit from the same parent.
class A { }
class B extends A { }
class C extends A { }
Enter fullscreen mode Exit fullscreen mode

🚫 Note: Java does not support multiple inheritance with classes (to avoid ambiguity known as the diamond problem). Instead, you can use interfaces for that.


5️⃣ What’s Different from Composition 🧱

Inheritance: “is-a” relationship → Dog is an Animal

Composition: “has-a” relationship → Car has an Engine

// Inheritance
class Dog extends Animal { }

// Composition
class Car {
    Engine engine = new Engine();
}
Enter fullscreen mode Exit fullscreen mode

👉 Use inheritance for shared behavior, but composition for flexibility and decoupling.


6️⃣ The Whole Purpose of Inheritance 🎯

The main purpose of inheritance is to make your system easier to extend and maintain by reusing existing code logically.

It lets you define general behaviors once (in a parent class) and specialize them in subclasses when needed.

Inheritance helps you focus on “what makes this class different” rather than repeating “what’s already common.”


7️⃣ Common Mistakes & Best Practices 🧠

✅ Do:

Use inheritance only when a clear “is-a” relationship exists.

Keep parent classes focused and meaningful.

Override methods only when necessary.

🚫 Don’t:

Force inheritance just to reuse code — consider composition instead.

Create deep inheritance hierarchies (they become hard to maintain).

Forget to use super() when initializing parent class members.


8️⃣ Real-World Example 💼

Let’s model a simple employee system:

class Employee {
    String name;
    double salary;

    void displayDetails() {
        System.out.println(name + " earns $" + salary);
    }
}

class Manager extends Employee {
    int teamSize;

    void displayDetails() {
        super.displayDetails();
        System.out.println("Manages a team of " + teamSize);
    }
}

public class Company {
    public static void main(String[] args) {
        Manager m = new Manager();
        m.name = "Alice";
        m.salary = 90000;
        m.teamSize = 8;
        m.displayDetails();
    }
}
Enter fullscreen mode Exit fullscreen mode

Output:

Alice earns $90000.0
Manages a team of 8

Enter fullscreen mode Exit fullscreen mode

✅ Explanation:
The Manager class inherits from Employee and extends it with new behavior — no code duplication.


💬 Questions for You

When do you prefer inheritance over composition?

Have you ever faced issues due to deep inheritance chains?

Do you use interfaces to simulate multiple inheritance in your projects?

What’s the best way you’ve seen inheritance improve code reusability?

Top comments (0)