Sobes.tech
Junior — Middle

What is meant by polymorphism in object-oriented programming?

sobes.tech AI

Answer from AI

Polymorphism in object-oriented programming is the ability of objects of different classes to respond to the same messages (method calls) in different ways. Simply put, the same method can behave differently depending on the object that calls it.

For example, if there is a base class Animal with a method makeSound(), then subclasses Dog and Cat can implement this method in their own way:

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

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

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: Woof
        a2.makeSound(); // Outputs: Meow
    }
}

This is polymorphism — one interface, many implementations.

What is meant by polymorphism in object-oriented… - sobes.tech