Sobes.tech
Junior — Middle

Can you explain the main principles of object-oriented programming?

sobes.tech AI

Answer from AI

Principles of Object-Oriented Programming (OOP):

  1. Encapsulation — combining data and methods that operate on that data into a single object, hiding the internal implementation from the outside world.

  2. Inheritance — the ability to create 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) in different ways, allowing a single interface to be used for different data types.

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

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