Chapter 07 of 26

Inheritance

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 Manager is an Employee.

  • A Car is a Vehicle.

  • A SavingsAccount is a BankAccount.

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?

  1. Code reuse: common fields and methods are written once in the parent.

  2. Extensibility: new kinds of objects can be added by writing only the differences.

  3. 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.

  4. 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 people

Let's trace m.printPayslip() carefully, because it shows all three things a subclass can do:

  1. Manager has no printPayslip() of its own, so the inherited version from Employee runs.

  2. Inside it, getName() (also inherited) returns "Asha".

  3. It then calls monthlyPay(). The object is a Manager, and Manager overrides monthlyPay(), so the manager version runs.

  4. 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

super(args)

Call a parent constructor

Must be the first statement in the child constructor (Java 17)

super.method()

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 super.super

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 constructor

Construction 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 error

The 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 here

Output:

Vehicle constructed
Car constructed
--- using the car ---
Car destroyed
Vehicle destroyed

It 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

public / protected fields and methods

Yes

Usable directly in the subclass

Package-private (no modifier) members

Yes, if the subclass is in the same package

See Access Modifiers

private fields and methods

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 super(...), never inherited

static members

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 error

This 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
true

Python 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 error

A 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

class Manager extends Employee

super(name, salary);

C++

class Manager : public Employee

Member initializer list: Manager(...) : Employee(name, salary) { }

Python

class Manager(Employee):

super().__init__(name, salary)

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 True

One 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 inheritance

protected inheritance

private inheritance

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 ArrayList gives stack users methods like add(index, x) that break stack behaviour. Java's own Stack extends Vector is 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 public in C++. class Manager : Employee is private inheritance, and a Manager* will not convert to Employee* 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 uses class 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; final stops 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.