DEV Community

Kesavarthini
Kesavarthini

Posted on

Polymorphism in Java

πŸ“Œ What is Polymorphism?

Polymorphism means β€œmany forms.”

In Java, polymorphism allows the same method name to behave differently based on the situation.

🎯 Types of Polymorphism in Java

Java supports two types:

  • Compile-time Polymorphism (Method Overloading)
  • Runtime Polymorphism (Method Overriding)

1️⃣ Compile-Time Polymorphism (Method Overloading)

  • Same method name
  • Different parameters
  • Decision made at compile time

Example:

class Calculator {

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

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

public class Main {
    public static void main(String[] args) {
        Calculator c = new Calculator();
        System.out.println(c.add(5, 3));
        System.out.println(c.add(2.5, 3.5));
    }
}
Enter fullscreen mode Exit fullscreen mode

2️⃣ Runtime Polymorphism (Method Overriding)

  • Same method name
  • Same parameters
  • Different implementation in child class
  • Decision happens at runtime.

Example:

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

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

class Cat extends Animal {
    void sound() {
        System.out.println("Cat meows");
    }
}

public class Main {
    public static void main(String[] args) {
        Animal a;

        a = new Dog();
        a.sound();

        a = new Cat();
        a.sound();
    }
}

Enter fullscreen mode Exit fullscreen mode

Top comments (0)