Sobes.tech
Middle

Tell about the principles of OOP: encapsulation, inheritance, polymorphism, abstraction.

sobes.tech AI

Answer from AI

Object-Oriented Programming Principles:

  • Encapsulation — hiding the internal implementation of an object and providing access to data through methods. This protects the object's state from incorrect modification.

  • Inheritance — a mechanism that allows creating a new class based on an existing one, inheriting its properties and methods, which promotes code reuse.

  • Polymorphism — the ability of objects of different classes to respond to the same messages (methods) in different ways. In Python, this is achieved through method overriding in subclasses.

  • Abstraction — highlighting the essential characteristics of an object, hiding implementation details. In Python, abstract classes and methods from the abc module can be used.

Example in Python:

from abc import ABC, abstractmethod

class Animal(ABC):
    @abstractmethod
    def sound(self):
        pass

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

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

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

Here, Animal is an abstract class (abstraction), Dog and Cat inherit from it, implementing the sound method (inheritance and polymorphism). Encapsulation manifests in the fact that the internal data of the class can be hidden, and access to it is through methods.