JAVA - Zero to Hero / Object Oriented Programming (OOP)

Polymorphism

Polymorphism = "many forms"

In Java, it allows the same method name to perform different behaviors based on:

  • The number/type of arguments (Compile-time)

  • The actual object used at runtime (Runtime)

💡 Real-Life Analogy

A person acts differently in different roles: As a student, they attend class. As a friend, they hang out

→ One person, many behaviors — that's polymorphism.


🧠 Types of Polymorphism

Type

Achieved By

Decided When

Compile-time

Method Overloading

During compilation

Runtime

Method Overriding

During execution


🛠️ Compile-Time Polymorphism (Method Overloading)

🔸 Same method name, different parameters

class Calculator {
    int multiply(int a, int b) {
        return a * b;
    }

    int multiply(int a, int b, int c) {
        return a * b * c;
    }
}

public class Main {
    public static void main(String[] args) {
        Calculator c = new Calculator();
        System.out.println(c.multiply(2, 3));       // 6
        System.out.println(c.multiply(2, 3, 4));    // 24
    }
}
6
24

✅ Why use it?

To handle multiple versions of a method with different input types or counts.


🔁 Runtime Polymorphism (Method Overriding)

🔸 Same method name, same parameters, different behavior (due to inheritance)

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

class Cow extends Animal {
    void makeSound() {
        System.out.println("Cow says Moo");
    }
}

public class Main {
    public static void main(String[] args) {
        Animal a = new Cow();  // parent reference, child object
        a.makeSound();         // Cow’s version is called
    }
}
Cow says Moo

✅ Why use it?

To achieve dynamic behavior — the actual object decides which version of the method runs at runtime.


🔍 Key Differences

Feature

Overloading

Overriding

Based On

Parameters (count/type)

Object type (inheritance)

Class Relationship

Same class

Requires subclass & superclass

Timing

Compile-time

Runtime