Sobes.tech
Senior

Explain polymorphism.

sobes.tech AI

Answer from AI

Polymorphism is a principle of object-oriented programming that allows objects of different classes to have the same interface but different implementations of methods. This provides flexibility and extensibility of the code.

For example, you have a base class Animal with a method makeSound(). Derived classes Dog and Cat implement this method in their own way:

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

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

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

// Usage
Animal animal = new Dog();
animal.makeSound(); // Outputs: Woof

animal = new Cat();
animal.makeSound(); // Outputs: Meow

Thus, the same method call makeSound() behaves differently depending on the type of object the variable references.

Explain polymorphism. — QA / QA Automation - sobes.tech