Junior — Middle
Can you explain the basic principles and concepts of object-oriented programming?
sobes.tech AI
Answer from AI
Object-oriented programming (OOP) is based on several key principles:
- Encapsulation — combining data and methods that operate on that data into a single object, which allows hiding internal implementation details and protecting data.
- Inheritance — a mechanism that allows creating new classes based on existing ones, inheriting their properties and methods, which promotes code reuse.
- Polymorphism — the ability of objects of different classes to respond to the same messages (method calls) in different ways.
- Abstraction — highlighting the essential characteristics of an object while 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()) # Polymorphism: same method, different behavior