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:
- Understand Superclass and Subclass relationships.
- Master the
extendskeyword. - Use the
superkeyword to access parent methods.
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
class Parent { ... }
class Child extends Parent { ... }
Part 3 — Example
Problem: Create a basic Vehicle class and inherit it into a Car class.
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
class Child extends Parent {
Child() {
super(); // Calls Parent constructor
}
}
Part 3 — Example
Problem: Access a hidden parent variable.
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
- Create a base class
Employeewithsalary. - Create a subclass
Programmerwithbonus. - Calculate the total income (salary + bonus) and display it.
Step-by-Step Process
- Define
Employeewith a protected field for salary. - Inherit
Programmerand add the bonus field. - Instantiate
Programmerand set both values.
Expected Deliverables
EmployeeInheritance.javasource code.