Thursday, 12 June 2025

Polymorphism in Java

 

What is Polymorphism?

Polymorphism means “many forms.”
In Java, it allows one object to take many forms — like a parent type being used to refer to child objects.

👉 It makes your code flexible, reusable, and extensible.


Types of Polymorphism

  1. Compile-Time Polymorphism (Method Overloading)

  2. Run-Time Polymorphism (Method Overriding)


1. Compile-Time Polymorphism – Method Overloading

Same method name, different parameters (in same class).

class MathUtils {

    int add(int a, int b) {

        return a + b;

    }


    double add(double a, double b) {

        return a + b;

    }

}

 2. Run-Time Polymorphism – Method Overriding

A child class redefines a method from its parent.

Example:

class Animal {

    void makeSound() {

        System.out.println("Some sound");

    }

}


class Dog extends Animal {

    void makeSound() {

        System.out.println("Bark");

    }

}


Animal a = new Dog();
a.makeSound();  // Output: Bark

No comments:

Post a Comment

👨‍💻 How I Started Learning Java at 15 (and You Can Too)

  When I first heard of Java, I thought it was just something to do with Minecraft mods or Android apps. I didn’t realize it would become my...