Can you explain the main principles of object-oriented programming?
sobes.tech AI
Answer from AI
Object-oriented programming (OOP) is based on four main principles:
-
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.
-
Inheritance — a mechanism that allows creating 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, simplifying code extension and maintenance.
-
Abstraction — highlighting essential characteristics of an object while hiding implementation details to simplify interaction with the object.
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('Bobby');
dog.speak(); // Bobby barks.
Here, Dog inherits from Animal, overrides the speak method (polymorphism), and the name data is encapsulated within the object.