Sobes.tech
Middle

Are you familiar with composition in OOP? Tell about it.

sobes.tech AI

Answer from AI

Composition in OOP is a principle where one object contains another object and uses its functionality, instead of inheritance. This allows creating complex objects from simple components, increasing flexibility and reusability of code.

For example, instead of inheriting properties and methods, a class can have an instance of another class inside it and delegate some work to it.

Example in Python:

class Engine:
    def start(self):
        print("Engine started")

class Car:
    def __init__(self):
        self.engine = Engine()  # composition

    def start(self):
        self.engine.start()  # delegate call
        print("Car is moving")

car = Car()
car.start()

Here, Car contains an Engine object and uses its start method. This is more flexible than inheritance, as components can be changed dynamically.