Sobes.tech
Senior

Tell me about the principles of OOP

sobes.tech AI

Answer from AI

Principles of Object-Oriented Programming (OOP):

  1. Encapsulation — combining data and methods that work with that data into a single object, as well as hiding the internal implementation from the outside world. This allows protecting the object's state and managing access to it.

  2. Inheritance — a mechanism that allows creating new classes based on existing ones, inheriting their properties and methods. This promotes code reuse and hierarchical organization.

  3. Polymorphism — the ability of objects of different classes to respond differently to the same messages (method calls). This is achieved through method overriding and interfaces.

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

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} says: Woof!`);
  }
}

const dog = new Dog('Sharik');
dog.speak(); // Sharik says: Woof!

This demonstrates inheritance (Dog inherits from Animal), polymorphism (overriding the speak method), and encapsulation (the name property inside the object).

Tell me about the principles of OOP — Frontend - sobes.tech