Sobes.tech
Middle+

Name four principles of OOP.

sobes.tech AI

Answer from AI

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

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

  2. Inheritance — a mechanism that allows creating a new class based on an existing one, inheriting its properties and methods.

  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 to simplify interaction.

Example in Python:

class Animal:
    def speak(self):
        pass  # Abstract method

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

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

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