Sobes.tech
Intern — Middle

Can you explain the principles of object-oriented programming?

sobes.tech AI

Answer from AI

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

  1. Encapsulation — combining data and methods that operate on that data into a single object. This allows hiding internal implementation details and protecting data from direct external access.

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

  3. Polymorphism — the ability of objects of different classes to respond to the same messages (method calls) in different ways, simplifying code extension and maintenance.

  4. Abstraction — highlighting essential characteristics of an object while hiding non-essential details, helping to focus on important functionality.

Example in JavaScript (Node.js):

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('Bobic');
dog.speak(); // Bobic barks.

Here, the Dog class inherits from Animal, overrides the speak method (polymorphism), and data and methods are encapsulated within the class (encapsulation).