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:
- Master Method Overloading (Static Polymorphism).
- Master Method Overriding (Dynamic Polymorphism).
- Understand Dynamic Method Dispatch.
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
void display(int a) { ... }
void display(String b) { ... }
Part 3 — Example
Problem: Create a "Calculator" class with an overloaded add method.
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
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.
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
- Create a base class
Paymentwith a methodprocessPayment(double amount). - Create subclasses
CreditCardPaymentandUPIPaymentthat override the method. - In
CreditCardPayment, overloadprocessPaymentto accept an additional "transactionFee".
Step-by-Step Process
- Define the base class and method.
- Implement overriding in the child classes.
- Implement overloading in one of the child classes.
- Test by calling the methods using parent references.
Expected Deliverables
PolymorphicPayment.javasource code.