What is composition and how does it differ from inheritance?
sobes.tech AI
Answer from AI
Composition and inheritance are two different approaches to code reuse in object-oriented programming.
Inheritance involves creating a new class based on an existing one, where the new class automatically inherits the properties and methods of the parent. This is convenient when there is an "is-a" relationship, for example, a "Cat" class inherits from an "Animal" class.
Composition, on the other hand, is built on including objects of one class within another, meaning the new object contains other objects as parts. This reflects a "has-a" relationship. For example, a "Car" class may contain an object of the "Engine" class.
The main difference is that composition is more flexible and promotes loose coupling of components, which makes maintenance and extension of the code easier. In Python, composition is often implemented by passing objects to the constructor or setting attributes.
Example of composition:
class Engine:
def start(self):
print("Engine started")
class Car:
def __init__(self, engine):
self.engine = engine
def start(self):
self.engine.start()
print("Car is moving")
engine = Engine()
car = Car(engine)
car.start()
Here, the Car class uses an Engine object instead of inheriting from it.