Sobes.tech
Middle

Tell me about the principles of OOP: inheritance, polymorphism, encapsulation, abstraction.

sobes.tech AI

Answer from AI

Object-oriented programming (OOP) is based on four main principles:

  1. Inheritance — allows creating new classes based on existing ones, inheriting their properties and methods. This simplifies code reuse and the creation of object hierarchies.

  2. Polymorphism — the ability of objects of different classes to respond to the same messages (method calls) differently. For example, the draw() method can behave differently for Circle and Square objects.

  3. Encapsulation — hiding the internal implementation of an object and providing access to data only through public methods. This protects data from incorrect usage and simplifies maintenance.

  4. Abstraction — highlighting the essential characteristics of an object, hiding implementation details. It allows working with objects through their interfaces without delving into internal mechanisms.

Example in JavaScript:

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.`); // polymorphism
  }
}

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

Here, Dog inherits from Animal, overrides the speak method (polymorphism), and the name property is encapsulated within the object.