DEV Community

MANOJ K
MANOJ K

Posted on

Polymorphism in java

  • Polymorphism in Java is one of the core concepts in object-oriented programming (OOP) that allows objects to behave differently based on their specific class type.

  • The word polymorphism means having many forms, and it comes from the Greek words poly (many) and morph (forms), this means one entity can take many forms.

Real-Life Illustration of Polymorphism

  • Consider a person who plays different roles in life, like a father, a husband, and an employee. Each of these roles defines different behaviors of the person depending on the object calling it.

Types of Polymorphism

Compile-time Polymorphism (Method Overloading):

  • Achieved by defining multiple methods with the same name but different parameters within the same class.

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

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

    public static void main(String[] args) {
        OverloadingExample obj = new OverloadingExample();
        System.out.println("Sum of integers: " + obj.add(5, 10));
        System.out.println("Sum of doubles: " + obj.add(5.5, 10.5));
    }
}

Enter fullscreen mode Exit fullscreen mode

Runtime Polymorphism (Method Overriding):

  • Achieved when a subclass provides a specific implementation of a method already defined in its superclass.

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

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

public class OverridingExample {
    public static void main(String[] args) {
        Animal myAnimal = new Dog();
        myAnimal.sound(); // Outputs "Dog barks"
    }
}

Enter fullscreen mode Exit fullscreen mode

Reference

https://www.geeksforgeeks.org/java/polymorphism-in-java/
https://www.datacamp.com/doc/java/polymorphism

Top comments (0)