NBKRIST JavaHub – Polymorphism

Polymorphism in Java – Compile-time & Runtime

Polymorphism is one of the strongest pillars of Object-Oriented Programming. It allows one action to behave in multiple ways depending on the object. It makes Java flexible, scalable, and ideal for large applications.

1. What is Polymorphism?

Polymorphism means Many Forms. A single method call behaves differently depending on the actual object executing it.

Real-time Example (Automobile)

The action start() is common for all vehicles, but each behaves differently:

2. Compile-time Polymorphism (Method Overloading)

Compile-time polymorphism occurs when the method call is resolved during compilation. It is achieved through Method Overloading.

class Calculator { int add(int a, int b) { return a + b; } int add(int a, int b, int c) { return a + b + c; } }
30
60

Importance

3. Runtime Polymorphism (Method Overriding)

Runtime polymorphism occurs when the overridden method is chosen based on the object type during execution.

class Vehicle { void start() { System.out.println("Vehicle starting"); } } class Car extends Vehicle { @Override void start() { System.out.println("Car starting with key"); } } class ElectricCar extends Vehicle { @Override void start() { System.out.println("Electric Car starting silently"); } } public class Test { public static void main(String[] args){ Vehicle v; v = new Car(); v.start(); v = new ElectricCar(); v.start(); } }
Car starting with key
Electric Car starting silently

Importance

4. Difference: Compile-time vs Runtime Polymorphism

Compile-time Polymorphism Runtime Polymorphism
Achieved by method overloading Achieved by method overriding
Binding happens at compile-time Binding happens at runtime
Fast execution Slower (dynamic binding)
Decided by method signature Decided by object type
Suitable for utility & helper methods Suitable for extensible architectures

Practice Questions – Click to Reveal Answers

1️⃣ What is Polymorphism?
Polymorphism allows one method to perform differently depending on the object.
2️⃣ What is Compile-time Polymorphism?
Method overloading resolved during compilation.
3️⃣ What is Runtime Polymorphism?
Method overriding resolved by JVM at runtime.
4️⃣ Give a real-time example.
Different types of vehicles starting via the same start() method.
5️⃣ Why is Polymorphism important?
It supports flexibility, scalability, and extensibility in Java applications.

Quick Summary