Chapter 5 — Pillars of OOP: Inheritance

📚 Chapter Overview

Code reusability is a key goal of OOP. In this chapter, you will learn how to create a new class based on an existing class, inheriting its fields and methods using the extends keyword.

Learning Objectives:

5.1 Inheritance Basics

Part 1 — Definition

Inheritance is a mechanism in which one object acquires all the properties and behaviors of a parent object. The class that inherits is called a Subclass (or Child), and the class that is inherited from is the Superclass (or Parent). It promotes Code Reusability.

Part 2 — Syntax

Main.java
class Parent { ... }
class Child extends Parent { ... }

Part 3 — Example

Problem: Create a basic Vehicle class and inherit it into a Car class.

Main.java
class Vehicle {
    void honk() {
        System.out.println("Beep!");
    }
}

class Car extends Vehicle {
    String model = "Mustang";
}

public class Main {
    public static void main(String[] args) {
        Car myCar = new Car();
        myCar.honk(); // Accessing parent method
        System.out.println(myCar.model);
    }
}

Part 4 — Video

Video: Coming Soon


5.2 The 'super' Keyword

Part 1 — Definition

The super keyword is a reference variable which is used to refer to immediate parent class objects. It is mostly used to invoke the parent class constructor or methods when they are overridden in the child class.

Part 2 — Syntax

Main.java
class Child extends Parent {
    Child() {
        super(); // Calls Parent constructor
    }
}

Part 3 — Example

Problem: Access a hidden parent variable.

Animal.java
class Animal {
    String color = "White";
}
class Dog extends Animal {
    String color = "Black";
    void printColor() {
        System.out.println(color); // Prints Black
        System.out.println(super.color); // Prints White
    }
}

Part 4 — Video

Video: Coming Soon


🏆 Chapter Challenge

Challenge Objective

Build an "Employee Management System" using Inheritance.

Requirements

Step-by-Step Process

  1. Define Employee with a protected field for salary.
  2. Inherit Programmer and add the bonus field.
  3. Instantiate Programmer and set both values.

Expected Deliverables

Solve in Compiler