Junior — Middle
Can you explain the main principles of object-oriented programming?
sobes.tech AI
Answer from AI
The main principles of object-oriented programming (OOP) include:
- Encapsulation — combining data and methods that operate on that data into a single object, as well as hiding internal implementation details from the outside world.
- Inheritance — the ability to create new classes based on existing ones, inheriting their properties and methods, which promotes code reuse.
- Polymorphism — the ability of objects of different classes to respond to the same messages (method calls) in different ways, ensuring flexibility and extensibility.
- Abstraction — highlighting the essential characteristics of an object while hiding implementation details, simplifying interaction with the object.
In JavaScript (Node.js), OOP is implemented through prototypes and classes. For example:
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(); // Sharik barks.
Here, Dog inherits from Animal, overrides the speak method (polymorphism), and data and methods are encapsulated within classes.