Sobes.tech
Intern — Middle

Can you explain the 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 this 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. In C++, this is achieved through virtual functions.

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

Example in C++:

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

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

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