Sobes.tech
Junior — Middle

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:

  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. This is achieved through method overriding.

  4. Abstraction — highlighting the essential characteristics of an object while hiding implementation details, simplifying interaction with the object.

Example in C++:

class Animal {
public:
    virtual void sound() { std::cout << "Some sound" << std::endl; }
};

class Dog : public Animal {
public:
    void sound() override { std::cout << "Woof" << std::endl; }
};

int main() {
    Animal* a = new Dog();
    a->sound(); // Will output "Woof" thanks to polymorphism
    delete a;
    return 0;
}