Junior — Middle
Can you explain what the principle of composition means in object-oriented programming?
sobes.tech AI
Answer from AI
The principle of composition in object-oriented programming means building complex objects from simpler ones by including some objects inside others. Instead of inheritance, where a class extends another class, composition allows creating objects that contain other objects as their parts, delegating some functionality to them.
For example, if you have a class Car, it can contain an object of class Engine. Instead of Car inheriting from Engine, it simply uses it as part of itself. This increases flexibility and code reuse.
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() # delegation of call
car = Car()
car.start() # Output: Engine started
Thus, composition allows building complex objects from simple components, improving modularity and easing code maintenance.