Sobes.tech
Junior — Middle

Explain the concept of inheritance in object-oriented programming.

sobes.tech AI

Answer from AI

Inheritance in object-oriented programming is a mechanism that allows creating a new class (subclass) that inherits properties and methods from an existing class (superclass). This promotes code reuse and organization of hierarchies.

In JavaScript (and Node.js), inheritance is implemented through prototypes. With the introduction of classes (ES6), the syntax has become more familiar:

class Animal {
  constructor(name) {
    this.name = name;
  }
  speak() {
    console.log(`${this.name} makes a sound.`);
  }
}

class Dog extends Animal {
  speak() {
    console.log(`${this.name} barks.`);
  }
}

const dog = new Dog('Sharik');
dog.speak(); // Outputs: Sharik barks.

Here, the Dog class inherits properties and methods from the Animal class, while overriding the speak method. This allows creating specialized objects based on common templates.

Explain the concept of inheritance in object-oriented… - sobes.tech