DEV Community

Karthick Karthick
Karthick Karthick

Posted on

Understanding Polymorphism in Java: Types, Examples, and Real-Time Applications

Polymorphism in Java: A Complete Beginner's Guide
Introduction

Polymorphism is one of the four main principles of Object-Oriented Programming (OOP) in Java. The word Polymorphism comes from two Greek words: "Poly" meaning many and "Morph" meaning forms. It allows a single entity such as a method or object to take multiple forms.

In simple words, one name can have many behaviors.

What is Polymorphism in Java?

Polymorphism is the ability of an object or method to perform different actions based on the situation. It enables Java to use a single interface to represent different implementations.

*Why Do We Need Polymorphism?
*

Polymorphism is used to make programs more flexible, reusable, and easy to maintain.

Reasons for Using Polymorphism:

  • Code Reusability
  • The same method name can be reused for different tasks.
  • Flexibility
  • Allows one interface to work with multiple implementations.
  • Easy Maintenance
  • Changes can be made in one part of the program without affecting the entire application.
  • Extensibility
  • New classes and functionalities can be added easily.
  • Improved Readability
  • Makes the code cleaner and easier to understand.

Types of Polymorphism in Java:

  • Compile-Time Polymorphism
  • Runtime Polymorphism

Compile-Time Polymorphism (Static Polymorphism)

Compile-time polymorphism is achieved through Method Overloading. The compiler decides which method to call based on the number or type of parameters.
`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

}

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

    Calculator obj = new Calculator();

    System.out.println(obj.add(10, 20));
    System.out.println(obj.add(10, 20, 30));
    System.out.println(obj.add(10.5, 20.5));
}
Enter fullscreen mode Exit fullscreen mode

}`

Runtime Polymorphism (Dynamic Polymorphism)

Runtime polymorphism is achieved through Method Overriding. The method that gets executed is determined at runtime based on the actual object.
`class Animal {

void sound() {
    System.out.println("Animal makes a sound");
}
Enter fullscreen mode Exit fullscreen mode

}

class Dog extends Animal {

@Override
void sound() {
    System.out.println("Dog barks");
}
Enter fullscreen mode Exit fullscreen mode

}

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

    Animal obj = new Dog(); // Upcasting

    obj.sound();
}
Enter fullscreen mode Exit fullscreen mode

}`

Advantages of Polymorphism

  • Increases code reusability
  • Provides flexibility
  • Improves scalability
  • Makes applications easier to maintain
  • Supports dynamic method execution
  • Reduces code complexit

Top comments (0)