🌀 Polymorphism in Java – Explained Simply

🌀 Polymorphism in Java – Explained Simply

Polymorphism is an essential concept in Object-Oriented Programming (OOP) that means "many forms". In Java, polymorphism allows one interface to be used for different underlying forms (data types or behaviors).


🔑 Types of Polymorphism in Java

Type Also Called When It Happens Example
Compile-time Method Overloading At compile time Same method, different params
Runtime Method Overriding At runtime Subclass modifies parent method

1️⃣ Compile-Time Polymorphism (Method Overloading)

You define multiple methods with the same name but different parameter types or counts.

class MathUtils {
    int add(int a, int b) {
        return a + b;
    }

    double add(double a, double b) {
        return a + b;
    }
}

Usage:

MathUtils m = new MathUtils();
System.out.println(m.add(5, 3));       // Calls int version
System.out.println(m.add(5.0, 3.0));   // Calls double version

✅ Decision is made at compile time based on argument types.


2️⃣ Runtime Polymorphism (Method Overriding)

Occurs when a subclass provides a specific implementation of a method already defined in the parent class.

class Animal {
    void sound() {
        System.out.println("Some sound");
    }
}

class Dog extends Animal {
    @Override
    void sound() {
        System.out.println("Bark");
    }
}

Usage:

Animal a = new Dog();   // Parent reference, child object
a.sound();              // Output: Bark

✅ Decision is made at runtime based on the object type.


🧠 Polymorphism with Interfaces

interface Shape {
    void draw();
}

class Circle implements Shape {
    public void draw() {
        System.out.println("Drawing Circle");
    }
}

class Square implements Shape {
    public void draw() {
        System.out.println("Drawing Square");
    }
}

 

Usage:

Shape s1 = new Circle();
Shape s2 = new Square();

s1.draw(); // Drawing Circle
s2.draw(); // Drawing Square


📌 Summary

Concept Description
Polymorphism Same interface, multiple implementations
Compile-time Overloading methods (same class, different params)
Runtime Overriding methods (parent vs. child class)
Interfaces + Inheritance Enable powerful polymorphic behavior
Back to blog

Leave a comment

Please note, comments need to be approved before they are published.