
Java OOP – Chapter 5: Polymorphism in Java
In this lesson, you'll explore Polymorphism, a powerful concept in Java OOP that allows objects to take many forms. Polymorphism enables flexible code that can work with different object types through a common interface or superclass.
What is Polymorphism?
Polymorphism means "many forms." In Java, it refers to the ability of a single reference type (usually a parent class or interface) to refer to objects of different subtypes.
Java supports two main types of polymorphism:
Compile-time (Static): Achieved via method overloading
Run-time (Dynamic): Achieved via method overriding
Compile-time Polymorphism (Method Overloading)
Same method name, different parameter lists in the same class.
class Printer {
void print(String msg) {
System.out.println(msg);
}
void print(int num) {
System.out.println("Number: " + num);
}
}Usage:
Printer p = new Printer();
p.print("Hello");
p.print(123);Run-time Polymorphism (Method Overriding)
A subclass provides its own version of a method already defined in its superclass.
class Animal {
void makeSound() {
System.out.println("Animal makes sound");
}
}
class Dog extends Animal {
@Override
void makeSound() {
System.out.println("Dog barks");
}
}Dynamic Method Dispatch
A parent reference can refer to a child object, and the overridden method will be called at runtime.
Animal a = new Dog();
a.makeSound(); // Output: Dog barksEven though the reference is of type Animal, the actual object is a Dog.
What Cannot Be Overridden?
finalmethodsstaticmethods (they are hidden, not overridden)Constructors
Why Use Polymorphism?
Makes code flexible and extensible
Enables late binding and dynamic behavior
Helps you program to an interface, not implementation
Summary
Polymorphism allows one interface to be used for a variety of object types.
Overloading: same class, different parameters.
Overriding: subclass redefines a parent’s method.
Enables you to write flexible and reusable code.
Assignment: Lesson 5 – Polymorphism
Objective:
Understand and apply method overloading and overriding.
Part 1: Conceptual Questions
Answer these in comments or a separate file:
What is polymorphism in Java?
What is the difference between overloading and overriding?
Why is runtime polymorphism useful?
Part 2: Coding Task
Step 1 – Overloading:
Create a class Calculator with two methods:
add(int a, int b)returns the sum of two integers.add(double a, double b)returns the sum of two doubles.
Step 2 – Overriding:
Create a class Shape with a method area() that prints "Calculating area".
Then create a class Circle that extends Shape and overrides area() to print "Area of Circle = πr²".
In the main() method:
Call both overloaded
add()methods.Use a
Shapereference to callarea()on aCircleobject.
Github: https://github.com/tuanbeovnn/java-bootcamp/tree/java-bootcamp-oop-chapter5
