In a hospital, doctors, nurses and receptionists do very different work. Yet every one of them has a name and a staff ID, punches in at the start of a shift and punches out at the end. Write three separate classes and you copy that shared part three times, and fix every bug in it three times. Inheritance lets you write the shared part once and build each role on top of it.

In one line: a child class gets the fields and methods of its parent, and can add new ones or change (override) the ones it inherited.

Joining a hospital

Every new hospital employee goes through the same joining process: an ID card, an attendance account, a salary account. That is the Staff part. On top of it a doctor gets prescribing rights, a nurse gets access to the patient vitals system, and a receptionist gets the appointment desk. Nobody repeats the joining process for each role. Each role is "staff, plus something extra".

1. What Is Inheritance?

Inheritance builds a new class out of an existing one. The existing class is the parent, also called the base class or superclass. The new class is the child, also called the derived class or subclass.

The child starts with everything the parent has. From there it can use those methods as they are (a Doctor calls punchIn() without writing it), add fields and methods of its own (only a Doctor has prescribe()), or override an inherited method so it works differently for that child.

Inheritance describes an "is-a" relationship. A doctor is a staff member. A savings account is a bank account. If "X is a Y" sounds wrong when you say it out loud, inheritance is the wrong tool.

2. Why Inheritance Matters

Shared code gets written once and lives in the parent, which is the DRY (Don't Repeat Yourself) principle in action. When you fix a bug in the parent, every child picks up the fix automatically.

The class structure also mirrors how people think about the domain, so someone new to the code can find their way around quickly.

Most importantly, inheritance is what polymorphism is built on. Because every child is a parent, code written against the parent type works with every child. The next article is all about that.

3. How Inheritance Works

Take a bank. Every account has an account number, a holder and a balance, and every account supports deposits and withdrawals. A savings account also earns interest. A current account, the kind businesses use, is allowed to go below zero up to an overdraft limit, so it needs a different withdrawal rule.

These are the Java keywords you will use for inheritance:

Java
Inheritclass B extends A
Call parent constructorsuper(...) (first line)
Call parent methodsuper.method()
Mark an override@Override
Visible to children onlyprotected

Output

Priya deposited Rs.3000 -> balance Rs.15000
Priya earned interest Rs.75 -> balance Rs.15075
Priya: withdrawal of Rs.20000 declined (balance Rs.15075)
Ravi Traders withdrew Rs.12000 -> balance Rs.-7000 (overdraft in use)
Ravi Traders: withdrawal of Rs.5000 declined (overdraft limit Rs.10000)
SB-1001 | Priya | Rs.15075
CA-2001 | Ravi Traders | Rs.-7000

Look at what each child actually wrote. SavingsAccount has no deposit, withdrawal or summary code at all, yet Priya can use all three. The only thing it added is addMonthlyInterest(). CurrentAccount overrode withdraw() with its own rule, which is why Ravi Traders could take Rs.12000 out of a Rs.5000 balance while Priya could not take Rs.20000 out of Rs.15075. Both children call the parent constructor first with super(...), so the common fields are always set up in one place.

Two things are not inherited. Constructors are not: each class writes its own and calls the parent's. And a child cannot touch the parent's private members, even though those fields still exist inside the object. That is why balance is protected in this example. Be careful with protected, though. Every child can now change the balance directly, so the parent can no longer guard that rule on its own.

4. Types of Inheritance

TypeShapeExampleIn Java
SingleOne child, one parentSavingsAccount extends BankAccountYes
MultilevelA chain: the child is a parent for the next classEmployee → Developer → TechLeadYes
HierarchicalMany children, one parentSavings, Current and Fixed Deposit all extend BankAccountYes
MultipleOne child, many parentsSmartWatch is both a Watch and a FitnessBandNot for classes; a class can implement many interfaces instead

A mix of these, say hierarchical plus multiple, is sometimes called hybrid inheritance.

4.1 Multilevel Inheritance and Constructor Chaining

In a chain, each level adds a little more. When you create the most specific object, the constructors run from the top of the chain down. That makes sense: the parent part of an object has to exist before the child part can be built on it.

Output

1. Employee() sets up Anitha
2. Developer() adds language Java
3. TechLead() adds a team of 6
---
Anitha, codes in Java, leads 6 people
Is Anitha an Employee? yes

Each describe() calls the parent's version through super and then adds its own line. That is a safe, common way to override: extend what the parent does instead of throwing it away. Keep chains short, though. Two or three levels are easy to follow. At five, understanding one method means reading five classes.

4.2 Multiple Inheritance and the Diamond Problem

A smartwatch is a watch and also a fitness band, and both of those are devices. If Watch and FitnessBand each have a status() method, which one does SmartWatch get? And does it end up with one Device inside it, or two? This is the well-known diamond problem, named after the shape of the diagram.

Java sidesteps the question. A class can extend only one class, so the diamond cannot happen with classes. A class can implement as many interfaces as it likes, though, and if two of those interfaces provide a default method with the same signature, the compiler refuses to guess. It makes you override the method and choose. Inside your override you can still call a particular parent's version with Watch.super.status().

Output

Device setup runs once for Galaxy Fit
Time 10:30 | Steps 8200
Galaxy Fit battery: 80%

The Device setup runs once, and SmartWatch states clearly what status() means for it. In real designs, reach for interfaces or composition rather than trying to inherit from several classes.

5. When to Use Inheritance (and When Not To)

Inheritance is the tightest link you can create between two classes. The child depends on the parent's internals, and every change to the parent ripples down to every child. So use it only where it genuinely fits.

Inheritance is a good fit when

  • there is a real is-a relationship: a CurrentAccount is a BankAccount;
  • the child can stand in for the parent anywhere without surprising anyone (this is the Liskov Substitution Principle);
  • the children really do share data and behavior, and the hierarchy stays shallow, two or three levels at most.

Composition is the better choice when

  • the relationship is "has-a" or "uses-a". An electric scooter has a battery; it is not a battery. A report uses a printer; it is not a printer;
  • you need to swap behavior at runtime, like changing a scooter's battery pack or a report's printer. A parent class is fixed when you compile, but a field can be replaced;
  • you only want one or two methods. Inheriting an entire class to reuse one helper drags everything else along with it.

There is a classic trap here: Square extends Rectangle. In maths a square is a rectangle. But if Rectangle has setWidth() and setHeight(), a square cannot honour both independently, and code that expects a rectangle breaks when it gets a square. In code, "is-a" has to mean "behaves like", not just "is a kind of" in the dictionary sense.

You will often hear "favour composition over inheritance". It is good advice. Start with composition, and move to inheritance when a clear and stable is-a family shows up.

6. Practical Example: Payroll System

A company pays three kinds of people. Full-time employees get basic pay plus 40% HRA, minus 12% PF. Contractors are paid by the hour, minus 10% TDS. Interns get a fixed stipend. Every payslip must use the same layout, and the company expects to add more kinds of workers later.

Output

EMP-101 | Kiran | Full-time
  Basic 50000 + HRA 20000 - PF 6000 = Rs.64000
EMP-102 | Meena | Contractor
  120 hrs x Rs.800 - TDS 9600 = Rs.86400
EMP-103 | Arjun | Intern
  Stipend = Rs.15000
Total payroll: Rs.165400

Why This Design Works

The shared logic is written once. printPayslip() and the id, name and type fields live in Employee, so changing the payslip layout means changing one method.

Each child keeps its own rule to itself. HRA and PF exist only in FullTimeEmployee, TDS only in Contractor, and neither leaks into the other.

A new kind of worker is easy to add. A Consultant paid per project is one new class that extends Employee and overrides two methods. Nothing else changes.

And the payroll loop does not care what type anyone is. It treats everybody as an Employee, and each object works out its own pay. That is polymorphism, which the next article covers.

7. Common Mistakes

  • Inheriting just to reuse code. If "X is a Y" is not true, use composition, even when the two classes share a few methods.
  • Deep hierarchies. Five or more levels are hard to read and easy to break: a small change near the top can break classes far below.
  • Breaking the parent's promise. A child that throws "not supported" from an inherited method, or quietly changes what it means, is the Square / Rectangle trap all over again.
  • Too much protected state. Children that change parent fields directly can break the parent's rules. Give them protected methods that keep the checks in the parent instead.
  • Forgetting that the parent constructor must run first. In Java, super(...) has to be the first line of the child constructor. If you leave it out, Java calls the parent's no-argument constructor, and if the parent does not have one, the code does not compile.

Summary

Inheritance lets a child class reuse the fields and methods of a parent, add its own, and override what it needs to change. It models an is-a relationship, and the child has to work anywhere the parent is expected.

You met the four main shapes: single, multilevel, hierarchical and multiple. Java allows the first three for classes and handles the fourth through interfaces, which avoids the diamond problem. Constructors run from the parent down to the child, and super lets you extend the parent's behavior instead of replacing it. Keep hierarchies shallow, and choose composition for has-a relationships or whenever behavior needs to change at runtime.

Next comes polymorphism: how a single piece of code can work with many different types of objects.