-
Notifications
You must be signed in to change notification settings - Fork 4.9k
Closed
Description
🐛 Issue: Incorrect Example of Composition in OOP
Description:
The current example is intended to demonstrate composition in object-oriented programming, but it actually illustrates aggregation.
In the example:
engine = Engine(150)
wheel = Wheel("Alloy")
transmission = Transmission("Automatic")
car = Car(engine, wheel, transmission)The components Engine, Wheel, and Transmission are instantiated outside of the Car class and passed into it. This means they are not owned by the Car, and their lifetimes are not bound to the Car object. If the Car is deleted, these components may still exist—this is characteristic of aggregation, not composition.
✅ Corrected Example (Demonstrating Composition)
Here's a revised version where the Car class creates and owns its components. This ensures their lifetimes are tied to the Car, which correctly reflects composition:
class Engine:
def __init__(self, horsepower):
self.horsepower = horsepower
def start(self):
print(f"Engine started with {self.horsepower} HP.")
class Wheel:
def __init__(self, type):
self.type = type
def rotate(self):
print(f"The {self.type} wheel is rotating.")
class Transmission:
def __init__(self, type):
self.type = type
def shift_gear(self):
print(f"Transmission shifted: {self.type}")
class Car:
def __init__(self):
self.engine = Engine(150)
self.wheel = Wheel("Alloy")
self.transmission = Transmission("Automatic")
def drive(self):
self.engine.start()
self.wheel.rotate()
self.transmission.shift_gear()
print("Car is moving!")
# Example Usage
if __name__ == "__main__":
car = Car()
car.drive()✅ Summary
- The original example should be labeled as aggregation, not composition.
- The revised example properly demonstrates composition, where the
Carclass controls the creation and lifecycle of its components.
Request:
- Please update the documentation or code comments to clarify the difference, or replace the original example with the corrected one.
Metadata
Metadata
Assignees
Labels
No labels