Sobes.tech
Junior — Middle

Explain the main principles of object-oriented programming.

sobes.tech AI

Answer from AI

The main principles of object-oriented programming (OOP):

  1. Encapsulation — combining data and methods that operate on that data into a single object, hiding internal implementation details and exposing only necessary interfaces.

  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 (methods) differently, simplifying extensibility and maintenance.

  4. Abstraction — highlighting essential characteristics of an object, hiding implementation details to work with the object at a higher level.

Example in Python:

class Animal:
    def speak(self):
        pass

class Dog(Animal):
    def speak(self):
        return "Woof"

class Cat(Animal):
    def speak(self):
        return "Meow"

animals = [Dog(), Cat()]
for animal in animals:
    print(animal.speak())  # Polymorphism

These principles help create maintainable, scalable, and reusable code.