Inheritance

Lesson 0008 — 35 min read

Inheritance allows a class (subclass) to inherit the attributes and methods of another class (superclass). It promotes code reuse and establishes a hierarchical relationship.

School — Student Example

Student inherits printSchoolName() from School. The subclass can use parent methods as if they were its own.

class School {
    private String schoolName;

    School() { schoolName = "DPS"; }

    void printSchoolName() {
        System.out.println("School name: " + schoolName);
    }
}

class Student extends School {
    private String studentName;

    Student(String name) { this.studentName = name; }

    void printStudentName() {
        System.out.println("Student name: " + studentName);
    }
}

Student s = new Student("Raj");
s.printStudentName();  // Student name: Raj
s.printSchoolName();   // School name: DPS
class School {
private:
    string schoolName;

public:
    School() { schoolName = "DPS"; }

    void printSchoolName() {
        cout << "School name: " << schoolName << endl;
    }
};

class Student : public School {
private:
    string studentName;

public:
    Student(string name) { this->studentName = name; }

    void printStudentName() {
        cout << "Student name: " << studentName << endl;
    }
};

Student student("Raj");
student.printStudentName();  // Student name: Raj
student.printSchoolName();   // School name: DPS
class School:
    def __init__(self):
        self.__schoolName = "DPS"

    def printSchoolName(self):
        print("School name:", self.__schoolName)

class Student(School):
    def __init__(self, name):
        super().__init__()
        self.__studentName = name

    def printStudentName(self):
        print("Student name:", self.__studentName)

student = Student("Raj")
student.printStudentName()  # Student name: Raj
student.printSchoolName()   # School name: DPS

Parent vs Subclass

Types of Inheritance

1. Single Inheritance

One child inherits from one parent. One-to-one relationship.

class Animal {
    void eat() { System.out.println("This animal eats food."); }
}

class Dog extends Animal {
    void bark() { System.out.println("This dog barks."); }
}

Dog dog = new Dog();
dog.eat();   // This animal eats food.
dog.bark();  // This dog barks.
class Animal {
public:
    void eat() { cout << "This animal eats food." << endl; }
};

class Dog : public Animal {
public:
    void bark() { cout << "This dog barks." << endl; }
};

Dog dog;
dog.eat();   // This animal eats food.
dog.bark();  // This dog barks.
class Animal:
    def eat(self):
        print("This animal eats food.")

class Dog(Animal):
    def bark(self):
        print("This dog barks.")

dog = Dog()
dog.eat()   # This animal eats food.
dog.bark()  # This dog barks.

2. Multilevel Inheritance

A chain: Animal — Mammal — Dog. Each child inherits from its immediate parent.

class Animal {
    void eat() { System.out.println("This animal eats food."); }
}

class Mammal extends Animal {
    void walk() { System.out.println("This mammal walks."); }
}

class Dog extends Mammal {
    void bark() { System.out.println("This dog barks."); }
}

Dog dog = new Dog();
dog.eat();   // This animal eats food.
dog.walk();  // This mammal walks.
dog.bark();  // This dog barks.
class Animal {
public:
    void eat() { cout << "This animal eats food." << endl; }
};

class Mammal : public Animal {
public:
    void walk() { cout << "This mammal walks." << endl; }
};

class Dog : public Mammal {
public:
    void bark() { cout << "This dog barks." << endl; }
};

Dog dog;
dog.eat();   // This animal eats food.
dog.walk();  // This mammal walks.
dog.bark();  // This dog barks.
class Animal:
    def eat(self):
        print("This animal eats food.")

class Mammal(Animal):
    def walk(self):
        print("This mammal walks.")

class Dog(Mammal):
    def bark(self):
        print("This dog barks.")

dog = Dog()
dog.eat()   # This animal eats food.
dog.walk()  # This mammal walks.
dog.bark()  # This dog barks.

3. Hierarchical Inheritance

Multiple children inherit from one parent. One-to-many relationship.

class Animal {
    void eat() { System.out.println("This animal eats food."); }
}

class Dog extends Animal {
    void bark() { System.out.println("This dog barks."); }
}

class Cat extends Animal {
    void meow() { System.out.println("This cat meows."); }
}

Dog dog = new Dog();
Cat cat = new Cat();
dog.eat();  // This animal eats food.
dog.bark(); // This dog barks.
cat.eat();  // This animal eats food.
cat.meow(); // This cat meows.
class Animal {
public:
    void eat() { cout << "This animal eats food." << endl; }
};

class Dog : public Animal {
public:
    void bark() { cout << "This dog barks." << endl; }
};

class Cat : public Animal {
public:
    void meow() { cout << "This cat meows." << endl; }
};

Dog dog;
Cat cat;
dog.eat();   // This animal eats food.
dog.bark();  // This dog barks.
cat.eat();   // This animal eats food.
cat.meow();  // This cat meows.
class Animal:
    def eat(self):
        print("This animal eats food.")

class Dog(Animal):
    def bark(self):
        print("This dog barks.")

class Cat(Animal):
    def meow(self):
        print("This cat meows.")

dog = Dog()
cat = Cat()
dog.eat()   # This animal eats food.
dog.bark()  # This dog barks.
cat.eat()   # This animal eats food.
cat.meow()  # This cat meows.

Advantages of Inheritance

Important Concepts

Method Overriding

Subclass provides a specific implementation of a method already defined in the parent. Enables runtime polymorphism.

Rules:

super Keyword

Method Overloading vs Overriding

Aspect Overloading Overriding
Definition Same name, different params in same class Same name, same params in parent & child
Inheritance needed? No — within same class Yes — between parent and child
Parameters Must differ (number, type, or order) Must match exactly
Access modifier No restriction Cannot be more restrictive

Multiple Inheritance & Diamond Problem

Multiple inheritance — a class inherits from more than one parent. Java does NOT allow this with classes (only interfaces).

Diamond Problem — if B and C both inherit from A and override the same method, which version does D (inheriting both B and C) use? The ambiguity is why Java restricts this.

Code trace: What does this print?

class A {
    void show() { System.out.println("A"); }
}

class B extends A {
    void show() { System.out.println("B"); }
}

A ref = new B();
ref.show();

Which inheritance type does Animal — Mammal — Dog represent?

Notes

Inheritance :-

Inheritance ⇒ subclass inherits fields + methods from superclass

Goal ⇒ code reuse + hierarchical relationships

Terminology :-

Parent ⇒ class providing shared members (eg School)

Child ⇒ class inheriting from parent (eg Student)

Syntax ⇒ extends (Java) / : public (C++) / (Parent) (Python)

Types of Inheritance :-

a) Single ⇒ 1 parent — 1 child ; one-to-one relationship

b) Multilevel ⇒ chain (A — B — C) ; each child inherits from immediate parent

c) Hierarchical ⇒ 1 parent — many children ; one-to-many relationship

d) Multiple ⇒ many parents — 1 child (C++/Python supported ; disallowed for Java classes)

Diamond Problem :-

Ambiguity ⇒ B and C extend A and override method ; D extends B and C — which method runs?

Java solution ⇒ no multiple class inheritance ; multiple interface inheritance instead

Method Overriding :-

Overriding ⇒ child redefines parent method with exact same signature

Rules ⇒ same params ; same/less restrictive access ; cannot override private methods

super.method() ⇒ call parent version from child method

Overloading vs Overriding :-

Overloading ⇒ compile-time ; same class ; different parameter lists ; no inheritance required

Overriding ⇒ runtime ; parent-child ; exact same parameter lists ; inheritance required

Primary source: Oracle Java Tutorials — Inheritance. Ask me anything that's unclear.

← Prev: Access Modifiers Next: Polymorphism →

Questions? Ask your agent — you can follow up on any concept, quiz answer, or how this applies to a specific coding problem. Review the Java glossary or syntax quick reference for a compressed overview.