Sobes.tech
Junior — Middle

What is the significance of using polymorphism in object-oriented programming?

sobes.tech AI

Answer from AI

Polymorphism in object-oriented programming allows objects of different classes to respond to the same messages (method calls) in different ways. This increases the flexibility and extensibility of the code.

Example: there is a base class Animal with a method makeSound(). Derived classes Dog and Cat implement this method in their own way — the dog barks, the cat meows.

This allows writing code that works with objects of type Animal without worrying about the specific class:

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

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

class Cat extends Animal {
    @Override
    void makeSound() {
        System.out.println("Meow");
    }
}

public class Main {
    public static void main(String[] args) {
        Animal a1 = new Dog();
        Animal a2 = new Cat();
        a1.makeSound(); // Outputs Bark
        a2.makeSound(); // Outputs Meow
    }
}

Thus, polymorphism simplifies support and extension of programs by allowing the use of a single interface for different implementations.

What is the significance of using polymorphism in… - sobes.tech