Chapter 6 — Pillars of OOP: Polymorphism

📚 Chapter Overview

Polymorphism allows objects to take multiple forms. In this chapter, you will learn how to use Method Overloading (Compile-time) and Method Overriding (Runtime) to create flexible and dynamic code.

Learning Objectives:

6.1 Method Overloading

Part 1 — Definition

Method Overloading allows a class to have more than one method with the same name, as long as their parameter lists are different (different number of parameters or different types). This increases the readability of the program.

Part 2 — Syntax

Main.java
void display(int a) { ... }
void display(String b) { ... }

Part 3 — Example

Problem: Create a "Calculator" class with an overloaded add method.

Calculator.java
class Calculator {
    int add(int a, int b) { return a + b; }
    double add(double a, double b) { return a + b; }
}

public class Main {
    public static void main(String[] args) {
        Calculator calc = new Calculator();
        System.out.println(calc.add(5, 10));     // Calls int version
        System.out.println(calc.add(5.5, 10.5)); // Calls double version
    }
}

Part 4 — Video

Video: Coming Soon


6.2 Method Overriding

Part 1 — Definition

Method Overriding occurs when a subclass provides a specific implementation for a method that is already defined in its superclass. The method in the subclass must have the same name, return type, and parameters as the one in the parent.

Part 2 — Syntax

Main.java
class Parent {
    void show() { ... }
}
class Child extends Parent {
    @Override
    void show() { ... }
}

Part 3 — Example

Problem: Create a Shape hierarchy where each shape has its own draw method.

ShapeSystem.java
class Shape {
    void draw() { System.out.println("Drawing Shape"); }
}
class Circle extends Shape {
    void draw() { System.out.println("Drawing Circle"); }
}

public class Main {
    public static void main(String[] args) {
        Shape s = new Circle(); // Upcasting
        s.draw(); // Output: Drawing Circle
    }
}

Observation: Java decides which method to call at runtime based on the actual object type, not the reference type.

Part 4 — Video

Video: Coming Soon


🏆 Chapter Challenge

Challenge Objective

Build a "Payment System" that demonstrates both types of Polymorphism.

Requirements

Step-by-Step Process

  1. Define the base class and method.
  2. Implement overriding in the child classes.
  3. Implement overloading in one of the child classes.
  4. Test by calling the methods using parent references.

Expected Deliverables

Solve in Compiler