Inheritance in Java Explained with Real Time Examples

Related Courses

Inheritance in Java Explained with Real-Time Examples

From Rewriting Code to Building Family Trees of Behavior

Why Inheritance Exists (The Real Problem It Solves)

In the early stage of a project, writing separate code for every feature feels manageable. But as systems grow, patterns begin to repeat.
For example:

  • Every user has a name and email

  • Every employee has an ID and salary logic

  • Every product has a price and display behavior

If you write the same logic again and again, your program becomes harder to maintain. A small change in one place must be repeated in many files.

Inheritance was introduced to solve this duplication problem by allowing common behavior to live in one place and specialized behavior to live in another.

The Core Idea in Simple Terms

You create a parent class that holds common features.
Then you create child classes that add or change specific features.
This creates a natural “family” of related classes.

Real-World Example: User System in an Application

Imagine a software platform that has different types of users:

  • Admin

  • Teacher

  • Student

Step 1: Find What Is Common

All users share:

  • Name

  • Email

  • Login method

Step 2: Create a Parent Class

You design a User class that holds this shared logic.

Step 3: Create Specialized Classes

  • Admin can manage users

  • Teacher can create courses

  • Student can enroll in courses

Each child class inherits the basic features from User and adds its own role-specific behavior.
This avoids rewriting the same code three times.

How Java Implements Inheritance

Java uses a simple keyword:
extends
When you write:
class Student extends User
You are telling Java:
“Student should have everything User has, plus whatever I define here.”

This includes:

  • Variables

  • Methods

  • Access-controlled members

What Actually Gets Inherited

A child class receives:

  • Public members

  • Protected members

  • Default-access members (within the same package)

It does not directly access:

  • Private members

Private data still exists in the parent, but it must be accessed through parent methods.
This keeps data secure and controlled.

Method Overriding: Changing Behavior Safely

Sometimes, a child class needs to behave differently.

Example

A User might have:
displayRole() → “I am a user”
But an Admin should say:
“I am an admin”

Instead of creating a new method name, you override the parent’s method. This keeps the interface the same but changes the behavior.
This is one of the most powerful features of inheritance because it enables polymorphism.

Real-Time Example: Payment System

Parent Class: Payment

Common behavior:

  • Validate amount

  • Process transaction

Child Classes

  • CreditCardPayment

  • UPIPayment

  • WalletPayment

Each child:

  • Inherits validation logic

  • Implements its own transaction method

The system can treat all of them as Payment, but each behaves differently during processing.
This design allows you to add new payment types later without rewriting existing code.

The super Keyword (Talking to the Parent)

The word super lets a child class:

  • Call the parent’s constructor

  • Access the parent’s methods

Why This Matters

When an object is created, the parent part must be initialized before the child part. super ensures the base setup happens correctly.
Think of it like building a house:
You lay the foundation before decorating the rooms.

Constructor Flow in Inheritance

When you create a child object:

  1. Parent constructor runs first

  2. Child constructor runs next

This ensures the inherited parts are ready before the specialized parts begin.
Understanding this helps debug many “why is my value null?” problems.

Types of Inheritance in Java (Concept View)

Java supports:

  • Single inheritance (one parent, one child)

  • Multilevel inheritance (grandparent → parent → child)

  • Hierarchical inheritance (one parent, many children)

Java avoids multiple class inheritance to prevent complexity and confusion, but it allows multiple behavior inheritance through interfaces.

When NOT to Use Inheritance

Inheritance is powerful, but dangerous when misused.
Do NOT use inheritance just because classes look similar.

Use inheritance only when there is a strong:
“IS-A” relationship
For example:

  • A Car IS-A Vehicle → Good

  • A Car IS-A Engine → Wrong

If the relationship is more like:
“HAS-A”
Then composition is better than inheritance.

Real-Time Example: Notification System

Better design:

  • Notification class

  • EmailService class

  • SMSService class

A notification uses these services. It does not “become” them.
This avoids rigid inheritance trees.

Access Control and Safety

Inheritance works closely with access modifiers:

  • public → everyone can access

  • protected → child classes can access

  • default → same package only

  • private → only the parent can access

Good design uses protected sparingly to avoid exposing too much internal logic.

Why Interviewers Focus on Inheritance

They are not testing syntax. They are testing:

  • Design judgment

  • Relationship modeling

  • Future-proof thinking

  • Code maintainability

A correct definition is good.
A correct example and design choice is better.

Beginner Mistakes with Inheritance

Common problems include:

  • Making everything extend everything

  • Ignoring constructors

  • Forgetting to use @Override

  • Exposing parent data as public

  • Creating deep inheritance chains

Professional developers prefer shallow, clear hierarchies.

How Inheritance Supports Polymorphism

When you store child objects in a parent reference, Java decides at runtime which method to run.
This allows:

  • Flexible design

  • Plugin-style architecture

  • Easy system expansion

This is how large frameworks stay adaptable.

Quick Revision Summary

  • Inheritance allows code reuse and specialization

  • Use extends to create a child class

  • Child gets public and protected members

  • Override methods to change behavior

  • Use super to access parent logic

  • Prefer composition for “HAS-A” relationships

  • Keep inheritance hierarchies simple

FAQ - Interview and Beginner Friendly

1.Can Java support multiple inheritance?
Not with classes. Java uses interfaces to support multiple behavior inheritance.

2.Why are parent variables often private?
To protect data and enforce access through controlled methods.

3.What happens if I don’t call super()?
Java automatically calls the default parent constructor if one exists.

4.Can constructors be inherited?
No. Constructors are not inherited, but they are called during object creation.

5.What is method overriding used for?
To change or customize parent behavior in child classes.

6.When should I avoid inheritance?
When the relationship is not truly “IS-A.”

7.What is the final keyword’s role?
It prevents a class or method from being extended or overridden.

8.What is upcasting?
Treating a child object as a parent reference.

9.Why is deep inheritance bad?
It makes systems hard to understand, test, and modify.

10.What shows real mastery of inheritance?
Knowing when NOT to use it. Master these design decisions in a structured Java course at NareshIT.

Final Thought

Inheritance in Java is not about saving lines of code.
It is about building relationships between concepts in a system.

When used well, it creates elegant, flexible software.
When misused, it creates rigid, fragile systems.

The true skill is not knowing how to extend a class It is knowing whether you should.