0
0
Javaprogramming~5 mins

Why polymorphism is needed in Java

Choose your learning style9 modes available
Introduction

Polymorphism helps us use one interface to work with different types of objects. It makes code easier to write and change.

When you want to use the same method name for different actions depending on the object.
When you want to write code that works with many types of objects without changing it.
When you want to add new object types without changing existing code.
When you want to simplify complex code by treating different objects in a similar way.
Syntax
Java
class Animal {
    void sound() {
        System.out.println("Animal makes a sound");
    }
}

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

class Cat extends Animal {
    @Override
    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();
    }
}

Polymorphism is often done using method overriding in Java.

It allows one variable to refer to objects of different classes.

Examples
The variable a is of type Animal but holds a Dog object. The sound() method of Dog runs.
Java
Animal a = new Dog();
a.sound();  // Prints: Dog barks
Here, a holds a Cat object, so Cat's sound() runs.
Java
Animal a = new Cat();
a.sound();  // Prints: Cat meows
If a holds an Animal object, the base method runs.
Java
Animal a = new Animal();
a.sound();  // Prints: Animal makes a sound
Sample Program

This program shows how one variable a can hold different objects and call their own sound() methods. This is polymorphism in action.

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

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

class Cat extends Animal {
    @Override
    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();
        a = new Animal();
        a.sound();
    }
}
OutputSuccess
Important Notes

Polymorphism helps keep code flexible and easy to extend.

It reduces the need for many if or switch statements.

Summary

Polymorphism lets one name work for many forms.

It allows writing general code that works with many object types.

This makes programs easier to maintain and grow.