Sobes.tech
Junior — Middle

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

sobes.tech AI

Answer from AI

The main goal of polymorphism in object-oriented programming is to enable the use of objects of different classes through a unified interface, allowing methods to be called that behave differently depending on the specific type of the object.

This simplifies the extensibility and maintenance of code, as you can write general code without worrying about specific implementations. For example, a method can accept a parameter of a base class, but in reality, it works with objects of derived classes, calling overridden methods.

Example in Java:

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

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

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

public class Main {
    public static void main(String[] args) {
        Animal a = new Dog();
        a.sound(); // Outputs "Bark"

        a = new Cat();
        a.sound(); // Outputs "Meow"
    }
}
What is the main purpose of using polymorphism in… - sobes.tech