Sobes.tech
Middle

What is OOP and its main principles?

sobes.tech AI

Answer from AI

Object-oriented programming (OOP) is a programming paradigm based on the use of objects, which combine data and methods to work with that data.

Main principles of OOP:

  1. Encapsulation — combining data and methods into a single object, hiding internal implementation, and providing access through an interface.

  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.

  4. Abstraction — highlighting the essential characteristics of an object, hiding implementation details.

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())  # Demonstrates polymorphism