Middle+
Name four principles of OOP.
sobes.tech AI
Answer from AI
Four main principles of object-oriented programming (OOP):
-
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.
-
Inheritance — a mechanism that allows creating a new class based on an existing one, inheriting its properties and methods.
-
Polymorphism — the ability of objects of different classes to respond to the same messages (methods) in different ways.
-
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