Imagine you are building payroll software for a company. You write an Employee class with a name, a salary and a method to print a payslip. Then the HR team says: "Managers are employees too, but they also conduct reviews and get a team allowance." Should you copy the whole Employee class and edit it? No. You let Manager inherit from Employee and write only what is different.
That is inheritance, the third pillar of OOP. In this chapter we'll see what it is, how it works in memory and in constructors, what does and doesn't get inherited, and when you should not use it. The different shapes an inheritance hierarchy can take (multilevel, multiple, hybrid ...) are covered in the next chapter, Types of Inheritance.
What Is Inheritance?
Inheritance is a mechanism by which one class (the subclass, child or derived class) acquires the fields and methods of another class (the superclass, parent or base class). The subclass can use the inherited members, add new members and override inherited methods to change their behaviour.
Inheritance models an IS-A relationship:
A
Manageris anEmployee.A
Caris aVehicle.A
SavingsAccountis aBankAccount.
If the sentence "X is a Y" sounds wrong, inheritance is probably the wrong tool. A Car is not an Engine; it has an engine.
+--------------------+
| Employee | superclass (general)
|--------------------|
| name, baseSalary |
| monthlyPay() |
| printPayslip() |
+--------------------+
▲
| extends ("is-a")
|
+--------------------+
| Manager | subclass (specialised)
|--------------------|
| teamSize | + new field
| conductReview() | + new method
| monthlyPay() | ~ overridden method
+--------------------+The arrow points from the child to the parent, which is also how UML draws it. The parent is more general; the child is more specialised.
Why Use Inheritance?
Code reuse: common fields and methods are written once in the parent.
Extensibility: new kinds of objects can be added by writing only the differences.
Polymorphism: a parent-type variable can hold any child object, so one piece of code can handle many types. This is the most important benefit, and the topic of Polymorphism.
Modelling the domain: class hierarchies often mirror real categories, which makes the code easier to understand.
Inheritance in Java: A Complete Example
In Java we use the extends keyword.
class Employee {
private final String name;
protected double baseSalary;
Employee(String name, double baseSalary) {
this.name = name;
this.baseSalary = baseSalary;
}
String getName() { return name; }
double monthlyPay() { return baseSalary; }
void printPayslip() {
System.out.println(getName() + " -> Rs." + monthlyPay());
}
}
class Manager extends Employee {
private final int teamSize;
Manager(String name, double baseSalary, int teamSize) {
super(name, baseSalary); // build the Employee part first
this.teamSize = teamSize;
}
// new behaviour that only managers have
void conductReview() {
System.out.println(getName() + " is reviewing " + teamSize + " people");
}
// changed behaviour: managers get Rs.2000 per team member
@Override
double monthlyPay() {
return super.monthlyPay() + 2000 * teamSize;
}
}
public class InheritanceDemo {
public static void main(String[] args) {
Employee e = new Employee("Ravi", 40000);
Manager m = new Manager("Asha", 60000, 5);
e.printPayslip();
m.printPayslip(); // inherited method, overridden monthlyPay()
m.conductReview(); // Manager's own method
}
}Output:
Ravi -> Rs.40000.0
Asha -> Rs.70000.0
Asha is reviewing 5 peopleLet's trace m.printPayslip() carefully, because it shows all three things a subclass can do:
Managerhas noprintPayslip()of its own, so the inherited version fromEmployeeruns.Inside it,
getName()(also inherited) returns"Asha".It then calls
monthlyPay(). The object is aManager, andManageroverridesmonthlyPay(), so the manager version runs.That version calls
super.monthlyPay()(60000) and adds 2000 × 5 = 10000, giving 70000.
And conductReview() is a member the subclass added. An ordinary Employee object doesn't have it.
The super Keyword
super refers to the parent part of the current object. It has two uses:
Form | Meaning | Rule |
|---|---|---|
| Call a parent constructor | Must be the first statement in the child constructor (Java 17) |
| Call the parent's version of a method, typically from inside an override | Runs the version the direct parent has (declared there or inherited from higher up); there is no |
A note on versions: Java 25 finalised flexible constructor bodies (JEP 513), which relaxes the "first statement" rule: statements that don't use the object being built (for example, validating an argument) may appear before super(...). Since most university courses and placement tests still use Java 17 or 21, follow the classic rule.
Constructor Chaining: Parents Are Built First
An object of a subclass contains a parent part. Before the child's constructor body runs, the parent part must be initialised. So Java always calls a parent constructor first. If you don't write super(...), the compiler silently inserts super() (with no arguments).
class Vehicle {
Vehicle() { System.out.println("1. Vehicle constructor"); }
}
class Car extends Vehicle {
Car() { System.out.println("2. Car constructor"); }
}
class ElectricCar extends Car {
ElectricCar() { System.out.println("3. ElectricCar constructor"); }
}
public class ChainDemo {
public static void main(String[] args) {
new ElectricCar();
}
}Output:
1. Vehicle constructor
2. Car constructor
3. ElectricCar constructorConstruction runs from the top of the hierarchy down. (Strictly, Object() runs even before Vehicle().)
This automatic super() causes a classic compile error. If the parent has only a constructor with parameters, there is no no-arg constructor to call:
class Employee {
Employee(String name) { }
}
class Intern extends Employee {
Intern() { } // no explicit super(...) call
}SuperErr.java:6: error: constructor Employee in class Employee cannot be applied to given types;
Intern() { } // no explicit super(...) call
^
required: String
found: no arguments
reason: actual and formal argument lists differ in length
1 errorThe fix is to call the right parent constructor explicitly, e.g. Intern() { super("Trainee"); }.
C++: constructors down, destructors up
C++ follows the same order for construction and the reverse order for destruction:
#include <iostream>
class Vehicle {
public:
Vehicle() { std::cout << "Vehicle constructed\n"; }
~Vehicle() { std::cout << "Vehicle destroyed\n"; }
};
class Car : public Vehicle {
public:
Car() { std::cout << "Car constructed\n"; }
~Car() { std::cout << "Car destroyed\n"; }
};
int main() {
Car c;
std::cout << "--- using the car ---\n";
} // c goes out of scope hereOutput:
Vehicle constructed
Car constructed
--- using the car ---
Car destroyed
Vehicle destroyedIt makes sense: the child may depend on the parent part, so the parent must exist first and be destroyed last. This is a very common viva and GATE question.
What Is (and Isn't) Inherited?
Member | Inherited in Java? | Notes |
|---|---|---|
| Yes | Usable directly in the subclass |
Package-private (no modifier) members | Yes, if the subclass is in the same package | See Access Modifiers |
| Not accessible | The private fields still exist inside the child object (memory is allocated for them), but child code cannot name them |
Constructors | No | They are called through |
| Accessible through the subclass | But static methods are hidden, not overridden (see Method Overloading vs Method Overriding) |
Trying to use a private parent field from the child:
class Employee {
private String name;
Employee(String name) { this.name = name; }
}
class Intern extends Employee {
Intern(String name) { super(name); }
void hello() {
System.out.println("Hi " + name);
}
}PrivateErr.java:9: error: name has private access in Employee
System.out.println("Hi " + name);
^
1 errorThis is encapsulation protecting the parent. The child should use a public or protected method such as getName().
Memory picture of a Manager object
+-------------------------------------+
| Employee part |
| name = "Asha" (private) | ← exists, but Manager code can't touch it
| baseSalary = 60000 (protected) |
|-------------------------------------|
| Manager part |
| teamSize = 5 |
+-------------------------------------+Object: The Root of Every Java Class
In Java every class that doesn't say extends implicitly extends java.lang.Object. So every object inherits methods like toString(), equals(), hashCode() and getClass().
class Point {
int x = 3, y = 4;
}
public class ObjectDemo {
public static void main(String[] args) {
Point p = new Point();
Object o = p; // every class IS-A Object
System.out.println(o.getClass().getName());
System.out.println(p.equals(p));
System.out.println(p instanceof Object);
}
}Output:
Point
true
truePython is similar: every class ultimately inherits from object. C++ has no common root class.
Preventing Inheritance: final
Sometimes a class must not be extended, for security or correctness. String in Java is final for exactly this reason. Mark your own class final and the compiler blocks subclasses:
final class Money { }
class Rupee extends Money { }FinalErr.java:3: error: cannot inherit from final Money
class Rupee extends Money { }
^
1 errorA final method can be inherited but not overridden. C++11 and later have the same idea: class Money final { ... };.
Inheritance in C++ and Python
Same idea, different syntax:
Language | Syntax | Call parent constructor |
|---|---|---|
Java |
|
|
C++ |
| Member initializer list: |
Python |
|
|
The Python version of our payroll example:
class Employee:
def __init__(self, name, base_salary):
self.name = name
self.base_salary = base_salary
def monthly_pay(self):
return self.base_salary
class Manager(Employee):
def __init__(self, name, base_salary, team_size):
super().__init__(name, base_salary)
self.team_size = team_size
def monthly_pay(self):
return super().monthly_pay() + 2000 * self.team_size
m = Manager("Asha", 60000, 5)
print(m.name, m.monthly_pay())
print(isinstance(m, Employee), issubclass(Manager, object))Output:
Asha 70000
True TrueOne Python trap: if the child defines __init__ and forgets to call super().__init__(...), the parent's attributes are simply never created. Python does not insert the call for you as Java does.
C++ inheritance modes
C++ adds something Java doesn't have: the mode of inheritance controls how inherited members are seen from outside.
Base member is |
|
|
|
|---|---|---|---|
public | public | protected | private |
protected | protected | protected | private |
private | not accessible | not accessible | not accessible |
Only public inheritance means "is-a". The default for class is private inheritance (for struct it is public), so always write public explicitly.
When Not to Use Inheritance
Inheritance is the tightest relationship between two classes: the child depends on the parent's internals, and any change in the parent ripples down. Use it only when:
The is-a test genuinely passes, and
A child object can be used anywhere a parent is expected without surprising anyone. (This is the Liskov Substitution Principle, covered later in the SOLID chapters.)
For "has-a" relationships, put an object inside another object instead (a Car has an Engine field). That is composition, and the advice "favour composition over inheritance" from the famous Gang of Four design-patterns book comes from this. Composition is explained fully in Association, Aggregation & Composition.
Common Mistakes
Inheriting just to reuse code.
class Stack extends ArrayListgives stack users methods likeadd(index, x)that break stack behaviour. Java's ownStack extends Vectoris a well-known example of this design mistake.Forgetting that constructors are not inherited. Every subclass must declare its own constructors and chain to the parent.
Assuming private members are "not there". They are in the object; they're just inaccessible to child code.
Deep hierarchies. Five or six levels of inheritance make code hard to follow. Prefer shallow hierarchies.
Forgetting
publicin C++.class Manager : Employeeis private inheritance, and aManager*will not convert toEmployee*outside the class.
Interview and GATE-Style Questions
What is inheritance and what relationship does it represent?
Inheritance lets a subclass acquire the members of a superclass and add or override behaviour. It represents an IS-A relationship, e.g. a Manager is an Employee.
Are constructors inherited in Java?
No. Constructors are not members that can be inherited. A subclass constructor must call a superclass constructor, either explicitly with super(...) or implicitly with the compiler-inserted super().
Are private members inherited?
Private fields are part of the subclass object in memory, but they are not accessible by name in the subclass. The Java Language Specification says private members are not inherited, in the sense that they are not members of the subclass. The child accesses them only through non-private methods of the parent.
In C++, class C derives from B, which derives from A. In which order are constructors and destructors called when a C object is created and destroyed?
Constructors: A, then B, then C. Destructors: C, then B, then A (reverse order).
What happens if the parent class has only a parameterised constructor and the child constructor doesn't call super(...)?
Compile error. The compiler inserts super(), but there is no no-argument constructor in the parent, so it reports "constructor ... cannot be applied to given types".
Which class is the superclass of all classes in Java?
java.lang.Object. Every class that does not extend another class extends Object implicitly.
How do you prevent a class from being inherited?
Declare it final in Java (final class Money) or C++11+ (class Money final). In Java you can also restrict which classes may extend it using sealed classes.
Summary
Inheritance lets a subclass reuse, extend and override the members of a superclass. It models IS-A.
Java uses
extends; C++ uses: public Base; Python usesclass Child(Parent).super(...)calls the parent constructor (first statement);super.method()calls the parent's version of a method.Constructors run parent first; C++ destructors run child first.
Constructors are not inherited; private members exist but are not accessible.
All Java classes extend
Object;finalstops a class from being extended.Use inheritance only for true is-a relationships; for has-a, use composition.
A hierarchy can grow in different directions: one parent with many children, chains of parents, or a child with several parents. Next, in Types of Inheritance, we'll look at each shape and at the famous diamond problem.