Sobes.tech
Junior

What is the meaning of polymorphism in programming?

sobes.tech AI

Answer from AI

Polymorphism allows the use of objects of different classes that share a common interface through a common "type" (for example, a base class or interface).

Its main purposes:

  • Unification of working with objects: Allows writing code that is independent of the specific object type and works with it through abstraction.
  • Flexibility: Easily add new classes that implement the same interface without changing existing code that uses this abstraction.
  • Readability and maintainability: The code becomes more structured and understandable, as the complexity of specific implementations is hidden behind a single interface.

The principle is that the same method, called on different objects, behaves differently depending on their specific type.

Example in PHP:

<?php

interface Animal {
    public function makeSound();
}

class Dog implements Animal {
    public function makeSound() {
        return "Woof!";
    }
}

class Cat implements Animal {
    public function makeSound() {
        return "Meow!";
    }
}

function hearAnimalSound(Animal $animal) {
    echo $animal->makeSound() . "\n";
}

$dog = new Dog();
$cat = new Cat();

hearAnimalSound($dog); // Outputs "Woof!"
hearAnimalSound($cat); // Outputs "Meow!"

?>

In this example, the function hearAnimalSound accepts any object that implements the Animal interface. Calling the makeSound() method inside this function behaves differently for Dog and Cat objects, demonstrating polymorphism.