Search code examples
inheritancecompositionclass-diagram

Vehicle and Car. Can i use composition or just inheritence?


I have a super class Vehicle, and subclasses car,van,bike. Can i use composition to this or is it just gonna be inheritence? Im drawing a class diagram


Solution

  • Broadly speaking, object composition models a “has-a” relationship between two objects. A car “has-a” transmission. Your computer “has-a” CPU. Inheritance models a "is a" relationship. A car "is a" vehicle.

    In this case, I think the relationship between a vehicle and a car/van/bike is better modeled by inheritance. A vehicle does not "have a" car. A car "is a" vehicle. So car/van/bike should all inherit their common properties from vehicle.