Sobes.tech
Junior — Middle

Can you explain the concept of polymorphism and its role in object-oriented programming?

sobes.tech AI

Answer from AI

Polymorphism is a principle of object-oriented programming that allows objects of different classes to be processed through a single interface. In simpler terms, the same method or function can work with objects of different types by invoking the appropriate implementation.

The role of polymorphism in OOP:

  • Allows writing more flexible and extensible code.
  • Simplifies support and addition of new classes without changing existing code.
  • Promotes the use of inheritance and interfaces.

Example in JavaScript (Node.js):

class Animal {
  speak() {
    console.log('Animal makes a sound');
  }
}

class Dog extends Animal {
  speak() {
    console.log('Bark');
  }
}

class Cat extends Animal {
  speak() {
    console.log('Meow');
  }
}

function makeAnimalSpeak(animal) {
  animal.speak();
}

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

makeAnimalSpeak(dog); // Bark
makeAnimalSpeak(cat); // Meow

Here, the function makeAnimalSpeak accepts an object of type Animal, but depending on the specific subclass, the corresponding implementation of the speak method is called.