Skip to main content

Inheritance — Code Reuse & Hierarchies

Editorial

Introduction

Encapsulation — Data Hiding Done Right kept each object's data safe, and Abstraction — Hiding Complexity let callers use a family of classes through one set of methods. So far, though, every class has been written from scratch, even when two classes share most of their code.

Take a program with Dog, Cat and Parrot classes. All of them have a name, an age and an eat() method. Without inheritance you would copy those into each class, and a change to eat() would then have to be made in every copy.

Inheritance lets you write the shared parts once, in a parent class (also called a superclass or base class), and have child classes (subclasses) receive them. Each child can then add its own parts or change the ones it received.

The test for using it is a plain sentence: "a Dog is an Animal", "a SavingsAccount is a BankAccount", "a Manager is an Employee". When that sentence sounds right, inheritance is usually the right tool. When it sounds forced, it usually is not, and the mistakes below show what goes wrong.

How Inheritance Works

A child class can do four things with what its parent has:

  1. Inherit it: the child gets the parent's attributes and methods without writing them again.
  2. Add to it: the child writes new attributes and methods that only it has.
  3. Override it: the child writes its own version of a parent's method, which replaces the parent's for that child.
  4. Extend it: the child writes its own version that calls the parent's version first and then does more.

Here is an employee system that uses all four. Employee is the parent. Manager, Developer and Intern are its children. Each language writes the parent link its own way; Go has no inheritance at all, so its listing gives each kind an embedded Employee and says so in a comment.

class Employee:
    """The parent class: what every employee has and does."""

    def __init__(self, name: str, employee_id: str, base_salary: float) -> None:
        self.name = name
        self.employee_id = employee_id
        self.base_salary = base_salary

    def calculate_pay(self) -> float:
        # The default pay: the base salary
        return self.base_salary

    def get_role(self) -> str:
        return "Employee"

    def display_info(self) -> None:
        print(f"[{self.get_role()}] {self.name} (ID: {self.employee_id})")
        print(f"  Pay: ${self.calculate_pay():.2f}")


class Manager(Employee):
    """A Manager is an Employee who also leads a team."""

    def __init__(self, name: str, employee_id: str, base_salary: float,
                 bonus_rate: float) -> None:
        # The parent's constructor sets the fields every employee shares
        super().__init__(name, employee_id, base_salary)
        self.bonus_rate = bonus_rate  # added: only a manager has a bonus rate

    def calculate_pay(self) -> float:
        # Overridden: a manager's pay is the base salary plus a bonus
        return self.base_salary + self.base_salary * self.bonus_rate

    def get_role(self) -> str:
        return "Manager"

    def approve_leave(self, employee_name: str) -> None:
        # Added: only a manager can approve leave
        print(f"  {self.name} approved leave for {employee_name}")


class Developer(Employee):
    """A Developer is an Employee who writes and reviews code."""

    def __init__(self, name: str, employee_id: str, base_salary: float,
                 is_senior: bool) -> None:
        super().__init__(name, employee_id, base_salary)
        self.is_senior = is_senior

    def calculate_pay(self) -> float:
        # Overridden: a senior developer earns 20% more than the base salary
        if self.is_senior:
            return self.base_salary * 1.20
        return self.base_salary

    def get_role(self) -> str:
        return "Senior Developer" if self.is_senior else "Developer"

    def code_review(self, pr_title: str) -> None:
        # Added: only a developer reviews code
        print(f"  {self.name} reviewed PR: '{pr_title}'")


class Intern(Employee):
    """An Intern is an Employee with a mentor; the stipend is the base salary."""

    def __init__(self, name: str, employee_id: str, stipend: float,
                 mentor: Employee) -> None:
        super().__init__(name, employee_id, stipend)
        self.mentor = mentor

    def get_role(self) -> str:
        return "Intern"

    # No calculate_pay here: an intern inherits Employee's, which pays the stipend

    def display_info(self) -> None:
        # Extended: the parent's lines first, then one more
        super().display_info()
        print(f"  Mentor: {self.mentor.name}")


manager = Manager("Sarah", "MGR-001", 120000, bonus_rate=0.15)
dev = Developer("James", "DEV-042", 95000, is_senior=True)
intern = Intern("Alex", "INT-007", 30000, mentor=dev)

# One loop for every kind of employee: each object runs its own class's version
for emp in [manager, dev, intern]:
    emp.display_info()
    print()

manager.approve_leave("James")
dev.code_review("Fix authentication bug")
import java.util.List;
import java.util.Locale;

// The parent class: what every employee has and does
class Employee {
    protected final String name;
    protected final String employeeId;
    protected final double baseSalary;

    Employee(String name, String employeeId, double baseSalary) {
        this.name = name;
        this.employeeId = employeeId;
        this.baseSalary = baseSalary;
    }

    public String getName() {
        return name;
    }

    // The default pay: the base salary
    public double calculatePay() {
        return baseSalary;
    }

    public String getRole() {
        return "Employee";
    }

    public void displayInfo() {
        System.out.println("[" + getRole() + "] " + name + " (ID: " + employeeId + ")");
        System.out.println(String.format(Locale.ROOT, "  Pay: $%.2f", calculatePay()));
    }
}

// A Manager is an Employee who also leads a team
class Manager extends Employee {
    private final double bonusRate; // added: only a manager has a bonus rate

    Manager(String name, String employeeId, double baseSalary, double bonusRate) {
        // The parent's constructor sets the fields every employee shares
        super(name, employeeId, baseSalary);
        this.bonusRate = bonusRate;
    }

    // Overridden: a manager's pay is the base salary plus a bonus
    @Override
    public double calculatePay() {
        return baseSalary + baseSalary * bonusRate;
    }

    @Override
    public String getRole() {
        return "Manager";
    }

    // Added: only a manager can approve leave
    public void approveLeave(String employeeName) {
        System.out.println("  " + name + " approved leave for " + employeeName);
    }
}

// A Developer is an Employee who writes and reviews code
class Developer extends Employee {
    private final boolean isSenior;

    Developer(String name, String employeeId, double baseSalary, boolean isSenior) {
        super(name, employeeId, baseSalary);
        this.isSenior = isSenior;
    }

    // Overridden: a senior developer earns 20% more than the base salary
    @Override
    public double calculatePay() {
        if (isSenior) {
            return baseSalary * 1.20;
        }
        return baseSalary;
    }

    @Override
    public String getRole() {
        return isSenior ? "Senior Developer" : "Developer";
    }

    // Added: only a developer reviews code
    public void codeReview(String prTitle) {
        System.out.println("  " + name + " reviewed PR: '" + prTitle + "'");
    }
}

// An Intern is an Employee with a mentor; the stipend is the base salary
class Intern extends Employee {
    private final Employee mentor;

    Intern(String name, String employeeId, double stipend, Employee mentor) {
        super(name, employeeId, stipend);
        this.mentor = mentor;
    }

    @Override
    public String getRole() {
        return "Intern";
    }

    // No calculatePay here: an intern inherits Employee's, which pays the stipend

    // Extended: the parent's lines first, then one more
    @Override
    public void displayInfo() {
        super.displayInfo();
        System.out.println("  Mentor: " + mentor.getName());
    }
}

public class InheritanceDemo {
    public static void main(String[] args) {
        Manager manager = new Manager("Sarah", "MGR-001", 120000, 0.15);
        Developer dev = new Developer("James", "DEV-042", 95000, true);
        Intern intern = new Intern("Alex", "INT-007", 30000, dev);

        // One loop for every kind of employee: each object runs its own class's version
        for (Employee emp : List.of(manager, dev, intern)) {
            emp.displayInfo();
            System.out.println();
        }

        manager.approveLeave("James");
        dev.codeReview("Fix authentication bug");
    }
}
#include <cstdio>
#include <string>
#include <utility>
#include <vector>

// The parent class: what every employee has and does
class Employee {
public:
    Employee(std::string name, std::string employeeId, double baseSalary)
        : name(std::move(name)), employeeId(std::move(employeeId)),
          baseSalary(baseSalary) {}
    virtual ~Employee() = default;

    const std::string& getName() const { return name; }

    // The default pay: the base salary
    virtual double calculatePay() const { return baseSalary; }

    virtual std::string getRole() const { return "Employee"; }

    virtual void displayInfo() const {
        std::printf("[%s] %s (ID: %s)\n", getRole().c_str(), name.c_str(),
                    employeeId.c_str());
        std::printf("  Pay: $%.2f\n", calculatePay());
    }

protected:
    std::string name;
    std::string employeeId;
    double baseSalary;
};

// A Manager is an Employee who also leads a team
class Manager : public Employee {
public:
    Manager(std::string name, std::string employeeId, double baseSalary,
            double bonusRate)
        // The parent's constructor sets the fields every employee shares
        : Employee(std::move(name), std::move(employeeId), baseSalary),
          bonusRate(bonusRate) {}

    // Overridden: a manager's pay is the base salary plus a bonus
    double calculatePay() const override { return baseSalary + baseSalary * bonusRate; }

    std::string getRole() const override { return "Manager"; }

    // Added: only a manager can approve leave
    void approveLeave(const std::string& employeeName) const {
        std::printf("  %s approved leave for %s\n", name.c_str(), employeeName.c_str());
    }

private:
    double bonusRate;  // added: only a manager has a bonus rate
};

// A Developer is an Employee who writes and reviews code
class Developer : public Employee {
public:
    Developer(std::string name, std::string employeeId, double baseSalary,
              bool isSenior)
        : Employee(std::move(name), std::move(employeeId), baseSalary),
          isSenior(isSenior) {}

    // Overridden: a senior developer earns 20% more than the base salary
    double calculatePay() const override {
        if (isSenior) {
            return baseSalary * 1.20;
        }
        return baseSalary;
    }

    std::string getRole() const override {
        return isSenior ? "Senior Developer" : "Developer";
    }

    // Added: only a developer reviews code
    void codeReview(const std::string& prTitle) const {
        std::printf("  %s reviewed PR: '%s'\n", name.c_str(), prTitle.c_str());
    }

private:
    bool isSenior;
};

// An Intern is an Employee with a mentor; the stipend is the base salary
class Intern : public Employee {
public:
    Intern(std::string name, std::string employeeId, double stipend,
           const Employee& mentor)
        : Employee(std::move(name), std::move(employeeId), stipend), mentor(mentor) {}

    std::string getRole() const override { return "Intern"; }

    // No calculatePay here: an intern inherits Employee's, which pays the stipend

    // Extended: the parent's lines first, then one more; C++ calls the parent by name
    void displayInfo() const override {
        Employee::displayInfo();
        std::printf("  Mentor: %s\n", mentor.getName().c_str());
    }

private:
    const Employee& mentor;
};

int main() {
    Manager manager("Sarah", "MGR-001", 120000, 0.15);
    Developer dev("James", "DEV-042", 95000, true);
    Intern intern("Alex", "INT-007", 30000, dev);

    // One loop for every kind of employee: each object runs its own class's version
    std::vector<const Employee*> team = {&manager, &dev, &intern};
    for (const Employee* emp : team) {
        emp->displayInfo();
        std::printf("\n");
    }

    manager.approveLeave("James");
    dev.codeReview("Fix authentication bug");
    return 0;
}
// The parent class: what every employee has and does
class Employee {
  constructor(
    protected readonly name: string,
    protected readonly employeeId: string,
    protected readonly baseSalary: number,
  ) {}

  getName(): string {
    return this.name;
  }

  // The default pay: the base salary
  calculatePay(): number {
    return this.baseSalary;
  }

  getRole(): string {
    return "Employee";
  }

  displayInfo(): void {
    console.log(`[${this.getRole()}] ${this.name} (ID: ${this.employeeId})`);
    console.log(`  Pay: $${this.calculatePay().toFixed(2)}`);
  }
}

// A Manager is an Employee who also leads a team
class Manager extends Employee {
  constructor(
    name: string,
    employeeId: string,
    baseSalary: number,
    private readonly bonusRate: number, // added: only a manager has a bonus rate
  ) {
    // The parent's constructor sets the fields every employee shares
    super(name, employeeId, baseSalary);
  }

  // Overridden: a manager's pay is the base salary plus a bonus
  override calculatePay(): number {
    return this.baseSalary + this.baseSalary * this.bonusRate;
  }

  override getRole(): string {
    return "Manager";
  }

  // Added: only a manager can approve leave
  approveLeave(employeeName: string): void {
    console.log(`  ${this.name} approved leave for ${employeeName}`);
  }
}

// A Developer is an Employee who writes and reviews code
class Developer extends Employee {
  constructor(
    name: string,
    employeeId: string,
    baseSalary: number,
    private readonly isSenior: boolean,
  ) {
    super(name, employeeId, baseSalary);
  }

  // Overridden: a senior developer earns 20% more than the base salary
  override calculatePay(): number {
    if (this.isSenior) {
      return this.baseSalary * 1.2;
    }
    return this.baseSalary;
  }

  override getRole(): string {
    return this.isSenior ? "Senior Developer" : "Developer";
  }

  // Added: only a developer reviews code
  codeReview(prTitle: string): void {
    console.log(`  ${this.name} reviewed PR: '${prTitle}'`);
  }
}

// An Intern is an Employee with a mentor; the stipend is the base salary
class Intern extends Employee {
  constructor(
    name: string,
    employeeId: string,
    stipend: number,
    private readonly mentor: Employee,
  ) {
    super(name, employeeId, stipend);
  }

  override getRole(): string {
    return "Intern";
  }

  // No calculatePay here: an intern inherits Employee's, which pays the stipend

  // Extended: the parent's lines first, then one more
  override displayInfo(): void {
    super.displayInfo();
    console.log(`  Mentor: ${this.mentor.getName()}`);
  }
}

const manager = new Manager("Sarah", "MGR-001", 120000, 0.15);
const dev = new Developer("James", "DEV-042", 95000, true);
const intern = new Intern("Alex", "INT-007", 30000, dev);

// One loop for every kind of employee: each object runs its own class's version
for (const emp of [manager, dev, intern]) {
  emp.displayInfo();
  console.log();
}

manager.approveLeave("James");
dev.codeReview("Fix authentication bug");
using System;
using System.Collections.Generic;
using System.Globalization;

// The parent class: what every employee has and does
public class Employee
{
    public string Name { get; }
    protected string EmployeeId { get; }
    protected double BaseSalary { get; }

    public Employee(string name, string employeeId, double baseSalary)
    {
        Name = name;
        EmployeeId = employeeId;
        BaseSalary = baseSalary;
    }

    // The default pay: the base salary
    public virtual double CalculatePay()
    {
        return BaseSalary;
    }

    public virtual string GetRole()
    {
        return "Employee";
    }

    public virtual void DisplayInfo()
    {
        Console.WriteLine($"[{GetRole()}] {Name} (ID: {EmployeeId})");
        string pay = CalculatePay().ToString("F2", CultureInfo.InvariantCulture);
        Console.WriteLine("  Pay: $" + pay);
    }
}

// A Manager is an Employee who also leads a team
public class Manager : Employee
{
    private readonly double bonusRate; // added: only a manager has a bonus rate

    // The parent's constructor sets the fields every employee shares
    public Manager(string name, string employeeId, double baseSalary, double bonusRate)
        : base(name, employeeId, baseSalary)
    {
        this.bonusRate = bonusRate;
    }

    // Overridden: a manager's pay is the base salary plus a bonus
    public override double CalculatePay()
    {
        return BaseSalary + BaseSalary * bonusRate;
    }

    public override string GetRole()
    {
        return "Manager";
    }

    // Added: only a manager can approve leave
    public void ApproveLeave(string employeeName)
    {
        Console.WriteLine($"  {Name} approved leave for {employeeName}");
    }
}

// A Developer is an Employee who writes and reviews code
public class Developer : Employee
{
    private readonly bool isSenior;

    public Developer(string name, string employeeId, double baseSalary, bool isSenior)
        : base(name, employeeId, baseSalary)
    {
        this.isSenior = isSenior;
    }

    // Overridden: a senior developer earns 20% more than the base salary
    public override double CalculatePay()
    {
        if (isSenior)
        {
            return BaseSalary * 1.20;
        }
        return BaseSalary;
    }

    public override string GetRole()
    {
        return isSenior ? "Senior Developer" : "Developer";
    }

    // Added: only a developer reviews code
    public void CodeReview(string prTitle)
    {
        Console.WriteLine($"  {Name} reviewed PR: '{prTitle}'");
    }
}

// An Intern is an Employee with a mentor; the stipend is the base salary
public class Intern : Employee
{
    private readonly Employee mentor;

    public Intern(string name, string employeeId, double stipend, Employee mentor)
        : base(name, employeeId, stipend)
    {
        this.mentor = mentor;
    }

    public override string GetRole()
    {
        return "Intern";
    }

    // No CalculatePay here: an intern inherits Employee's, which pays the stipend

    // Extended: the parent's lines first, then one more
    public override void DisplayInfo()
    {
        base.DisplayInfo();
        Console.WriteLine($"  Mentor: {mentor.Name}");
    }
}

public static class InheritanceDemo
{
    public static void Main()
    {
        var manager = new Manager("Sarah", "MGR-001", 120000, 0.15);
        var dev = new Developer("James", "DEV-042", 95000, true);
        var intern = new Intern("Alex", "INT-007", 30000, dev);

        // One loop for every kind of employee: each object runs its own class's version
        foreach (Employee emp in new List<Employee> { manager, dev, intern })
        {
            emp.DisplayInfo();
            Console.WriteLine();
        }

        manager.ApproveLeave("James");
        dev.CodeReview("Fix authentication bug");
    }
}
package main

import "fmt"

// Go has no inheritance. Each kind of employee embeds an Employee, which gives it
// the Employee's fields and methods, and the Worker interface lets one loop treat
// them alike.
type Worker interface {
	CalculatePay() float64
	GetRole() string
	DisplayInfo()
}

// Employee is what every employee has and does
type Employee struct {
	Name       string
	employeeID string
	baseSalary float64
}

// CalculatePay is the default pay: the base salary
func (e *Employee) CalculatePay() float64 {
	return e.baseSalary
}

func (e *Employee) GetRole() string {
	return "Employee"
}

func (e *Employee) DisplayInfo() {
	showInfo(e, e)
}

// showInfo prints the lines every employee shows. It is handed the Worker as well,
// because a method that comes from an embedded Employee calls Employee's own GetRole,
// never the outer type's: embedding does not override.
func showInfo(w Worker, e *Employee) {
	fmt.Printf("[%s] %s (ID: %s)\n", w.GetRole(), e.Name, e.employeeID)
	fmt.Printf("  Pay: $%.2f\n", w.CalculatePay())
}

// Manager is an Employee who also leads a team
type Manager struct {
	Employee
	bonusRate float64 // added: only a manager has a bonus rate
}

// NewManager sets the fields every employee shares through the embedded Employee
func NewManager(name, employeeID string, baseSalary, bonusRate float64) *Manager {
	return &Manager{Employee: Employee{name, employeeID, baseSalary}, bonusRate: bonusRate}
}

// CalculatePay is overridden: a manager's pay is the base salary plus a bonus
func (m *Manager) CalculatePay() float64 {
	return m.baseSalary + m.baseSalary*m.bonusRate
}

func (m *Manager) GetRole() string {
	return "Manager"
}

func (m *Manager) DisplayInfo() {
	showInfo(m, &m.Employee)
}

// ApproveLeave is added: only a manager can approve leave
func (m *Manager) ApproveLeave(employeeName string) {
	fmt.Printf("  %s approved leave for %s\n", m.Name, employeeName)
}

// Developer is an Employee who writes and reviews code
type Developer struct {
	Employee
	isSenior bool
}

func NewDeveloper(name, employeeID string, baseSalary float64,
	isSenior bool) *Developer {
	return &Developer{Employee: Employee{name, employeeID, baseSalary}, isSenior: isSenior}
}

// CalculatePay is overridden: a senior developer earns 20% more than the base salary
func (d *Developer) CalculatePay() float64 {
	if d.isSenior {
		return d.baseSalary * 1.20
	}
	return d.baseSalary
}

func (d *Developer) GetRole() string {
	if d.isSenior {
		return "Senior Developer"
	}
	return "Developer"
}

func (d *Developer) DisplayInfo() {
	showInfo(d, &d.Employee)
}

// CodeReview is added: only a developer reviews code
func (d *Developer) CodeReview(prTitle string) {
	fmt.Printf("  %s reviewed PR: '%s'\n", d.Name, prTitle)
}

// Intern is an Employee with a mentor; the stipend is the base salary
type Intern struct {
	Employee
	mentor *Employee
}

func NewIntern(name, employeeID string, stipend float64, mentor *Employee) *Intern {
	return &Intern{Employee: Employee{name, employeeID, stipend}, mentor: mentor}
}

func (i *Intern) GetRole() string {
	return "Intern"
}

// No CalculatePay here: an intern gets Employee's, which pays the stipend

// DisplayInfo is extended: the shared lines first, then one more
func (i *Intern) DisplayInfo() {
	showInfo(i, &i.Employee)
	fmt.Printf("  Mentor: %s\n", i.mentor.Name)
}

func main() {
	manager := NewManager("Sarah", "MGR-001", 120000, 0.15)
	dev := NewDeveloper("James", "DEV-042", 95000, true)
	intern := NewIntern("Alex", "INT-007", 30000, &dev.Employee)

	// One loop for every kind of employee: each value runs its own type's version
	for _, w := range []Worker{manager, dev, intern} {
		w.DisplayInfo()
		fmt.Println()
	}

	manager.ApproveLeave("James")
	dev.CodeReview("Fix authentication bug")
}

It prints:

[Manager] Sarah (ID: MGR-001)
  Pay: $138000.00

[Senior Developer] James (ID: DEV-042)
  Pay: $114000.00

[Intern] Alex (ID: INT-007)
  Pay: $30000.00
  Mentor: James

  Sarah approved leave for James
  James reviewed PR: 'Fix authentication bug'

Read the output against the code. Sarah's pay is 138000.00 because Manager overrides calculate_pay() to add the bonus. James is shown as a Senior Developer earning 114000.00 because Developer overrides both get_role() and calculate_pay(). Alex's pay is the stipend because Intern writes no calculate_pay() and inherits Employee's. Only Alex has a mentor line, because Intern extends display_info().

Look closely at Sarah's first line. display_info() belongs to Employee, yet it printed [Manager] and the manager's pay. That is because the parent's method calls self.get_role() and self.calculate_pay() on the object it was called on, and that object is a Manager. Python's tutorial describes exactly this: "Because methods have no special privileges when calling other methods of the same object, a method of a base class that calls another method defined in the same base class may end up calling a method of a derived class that overrides it."

The Java tutorial sums up what a child gets: "A subclass inherits all the members (fields, methods, and nested classes) from its superclass. Constructors are not members, so they are not inherited by subclasses, but the constructor of the superclass can be invoked from the subclass." That last part is why each child's constructor starts by calling its parent's.

The picture shows the hierarchy, what each child does with each method, and what each object printed.

Inherit, override, extend: a child gets its parent's methods, then adds, overrides or extends them. Employee holds what every employee shares: name, employee_id and base_salary, and calculate_pay(), get_role() and display_info(). Each child is an Employee. Manager overrides calculate_pay() to add a bonus, overrides get_role(), adds approve_leave() and inherits display_info(). Developer overrides calculate_pay() so a senior earns 20% more, overrides get_role(), adds code_review() and inherits display_info(). Intern inherits calculate_pay(), which pays the stipend, overrides get_role(), and extends display_info(): it calls super() first, then adds a line. The legend: to inherit uses the parent's method as it is, to override replaces the parent's version, to extend calls the parent's and then adds, and to add is a method only the child has. Each child's constructor hands the shared fields to Employee's through super().__init__(...), which sets the name, id and salary, and then sets its own, such as a manager's bonus_rate. Under each child, its object, its values and what the run printed: sarah, a Manager with a base salary of 120000 and a bonus rate of 0.15, paid 138000.00; james, a senior Developer with a base salary of 95000, printed as a Senior Developer and paid 114000.00; and alex, an Intern with a stipend of 30000 and the mentor james, paid 30000.00. Where one class is not an is-a of another, use composition instead.

Reaching the Parent with super()

A child reaches its parent through super(). It has two uses:

What you writeWhat it doesIn the listing
super().__init__(...)Runs the parent's constructorEach child sets the shared fields first
super().display_info()Runs the parent's version of a methodIntern prints the mentor line after it

The other languages say the same thing in their own words: Java and TypeScript write super, C# writes base, C++ names the parent (Employee::displayInfo()), and Go, which has no parent class, calls the shared code directly.

Intern.display_info() shows extending: it calls the parent's version through super() and then adds the mentor line. Manager.calculate_pay() shows overriding: it replaces the parent's version and never calls it. A useful rule of thumb is to override when the child's behaviour really is different, and to extend when the child does everything the parent does and then a little more.

Watch Python Find a Method

Here are the listing's four classes and its three objects. Pick sarah, james or alex, then press a method such as calculate_pay(), display_info() or approve_leave(employee_name). Watch where Python looks: in the object's own class first, then in Employee, then in object, the class every Python class comes from. Python's tutorial puts the rule this way: "if a requested attribute is not found in the class, the search proceeds to look in the base class." The console shows what Python's prompt prints for the same call.

A call is answered by the first class that writes the method: the object's own class, then Employee, then object. A method nobody writes ends in AttributeError.

Kinds of Inheritance

Classes can be arranged in a few shapes:

KindShapeExample
SingleOne parent, one childEmployee and Manager
MultilevelA chain of parentsAnimal, Dog and GoldenRetriever
HierarchicalOne parent, several childrenEmployee and its three kinds
MultipleOne child, several parentsDuck from Flyable and Swimmable

Python allows all four. Its tutorial says "Python supports a form of multiple inheritance as well." Java allows only one parent class: "Excepting Object, which has no superclass, every class has one and only one direct superclass (single inheritance)." A Java class can still implement any number of interfaces. The Java tutorial gives the reason for the limit: "One reason why the Java programming language does not permit you to extend more than one class is to avoid the issues of multiple inheritance of state, which is the ability to inherit fields from multiple classes."

Most of the classes in this course use single or hierarchical inheritance, as the employee system does.

Common Mistakes

Mistake 1: inheriting where there is no is-a. Java's own library has an example. Its documentation says that Stack "extends class Vector with five operations that allow a vector to be treated as a stack." Because a Stack inherits everything Vector has, it also offers get(index), insertElementAt and remove(index), which let any code reach into the middle of what should be a stack. A stack uses a vector to hold its items, but that does not make it a kind of vector. The same documentation points elsewhere: "A more complete and consistent set of LIFO stack operations is provided by the Deque interface and its implementations, which should be used in preference to this class." The better design gives the stack a list of its own and offers only push(), pop() and peek(). That is composition, and Composition vs Inheritance — Favor Composition covers it in full.

Mistake 2: forgetting the parent's constructor.

class Manager(Employee):
    def __init__(self, name, employee_id, base_salary, bonus_rate):
        self.bonus_rate = bonus_rate  # forgot super().__init__(...)

This Manager sets its own field and never calls Employee's constructor, so name, employee_id and base_salary are never set. Python does not complain when the object is made. The error comes later, far from the cause: a test on the listing's classes made this manager without a word and then failed on display_info() with AttributeError: 'Manager' object has no attribute 'name'. Java catches the same slip at compile time; javac stopped with constructor Employee in class Employee cannot be applied to given types;. The Java tutorial explains why: "If a constructor does not explicitly invoke a superclass constructor, the Java compiler automatically inserts a call to the no-argument constructor of the superclass. If the super class does not have a no-argument constructor, you will get a compile-time error." In Python, call super().__init__(...) first in every child's constructor.

Mistake 3: building tall hierarchies. A chain such as Animal, Mammal, DomesticMammal, Pet, Dog, SmallDog, Chihuahua is seven levels deep. A change to Animal reaches every level below it, and to understand Chihuahua you have to read six other classes first. Keep a hierarchy only as deep as the real is-a relationships, and combine behaviours through composition instead of adding levels. Refactoring: Deep Inheritance → Composition shows such a chain taken apart step by step.

Key Takeaways

  • Inheritance lets a child class receive its parent's attributes and methods, so shared code is written once. Use it only where "a child is a parent" is true.
  • A child can inherit a method as it is, add new ones, override one with its own version, or extend one by calling the parent's version through super() first.
  • A parent's method that calls another method on the same object runs the child's version when the child overrides it.
  • Call the parent's constructor first in every child's constructor; Python only fails later when you forget, and Java refuses to compile.
  • Polymorphism — Compile-Time vs Runtime comes next: using one call to work with many kinds of object.