DEV Community

Cover image for Polymorphism in Java
Kavitha
Kavitha

Posted on

Polymorphism in Java

Introduction
Polymorphism is one of the most important concepts of Object-Oriented Programming (OOPS) in Java.
The word Polymorphism comes from two Greek words:

  • Poly → Many
  • Morph → Forms In Java, polymorphism allows one method or object to perform different actions depending on the situation. ** What is Polymorphism?** Polymorphism means the same method name behaves differently based on:
  • Number of parameters
  • Type of parameters
  • Object reference at runtime

Types of Polymorphism in Java
Java supports two main types of polymorphism:

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

1. Compile-Time Polymorphism (Method Overloading)
Definition
When multiple methods have the same method name but different parameters in the same class, it is called method overloading.

✔ Resolved at compile time
Example:

class Calculator {

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

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

    double add(double a, double b) {
        return a + b;
    }
}
Enter fullscreen mode Exit fullscreen mode

Output Behavior

  • add(2,3) → calls first method
  • add(2,3,4) → calls second method
  • add(2.5,3.5) → calls third method

2. Runtime Polymorphism (Method Overriding)
Definition
When a child class provides its own implementation of a method already defined in the parent class, it is called method overriding.
✔ Resolved at runtime
✔ Achieved using inheritance

Example:

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

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

public class Test {
    public static void main(String[] args) {
        Animal a = new Dog();   // Upcasting
        a.sound();
    }
}
Enter fullscreen mode Exit fullscreen mode

Output:

Dog barks
Enter fullscreen mode Exit fullscreen mode

Top comments (0)