Sobes.tech
Junior — Middle

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

sobes.tech AI

Answer from AI

Polymorphism in object-oriented programming allows objects of different classes to be processed through a single interface, with each object able to implement behavior in its own way. This simplifies the extensibility and maintenance of code, and enables writing more flexible and reusable programs.

Example:

interface Animal {
    void sound();
}

class Dog implements Animal {
    public void sound() {
        System.out.println("Woof");
    }
}

class Cat implements Animal {
    public void sound() {
        System.out.println("Meow");
    }
}

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

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