OOP Fundamentals • Inheritance & CompositionMedium⏱️ ~3 min
Structure: Class Relationships and Diagrams
Inheritance Structure (▲ denotes inheritance)
In inheritance, subclasses extend a base class and inherit all its attributes and methods. The arrow points from child to parent.
Vehicle
- registrationNumber: String
- color: String
- color: String
+ start(): void
+ stop(): void
+ stop(): void
▲
Car
- numDoors: int
+ openTrunk(): void
Motorcycle
- hasSidecar: boolean
+ wheelie(): void
Composition Structure (◆ denotes composition)
In composition, the container object owns its components. Components cannot exist independently. The filled diamond points to the container.
Car
- engine: Engine
- transmission: Transmission
- transmission: Transmission
+ accelerate(): void
+ shiftGear(gear): void
+ shiftGear(gear): void
◆
Engine
- horsepower: int
- fuelType: String
- fuelType: String
+ ignite(): void
+ generatePower(): int
+ generatePower(): int
Transmission
- currentGear: int
- type: String
- type: String
+ shift(gear): void
+ getCurrentGear(): int
+ getCurrentGear(): int
Aggregation (◇ denotes aggregation)
Aggregation is a weaker form of composition where components can exist independently. The hollow diamond points to the container. A Department has Employees, but employees can exist without the department.
Key Difference: In composition, destroying the container destroys the components (Car destroyed means Engine destroyed). In aggregation, components survive independently (Department dissolved but Employees remain).
💡 Key Takeaways
✓Inheritance uses closed arrow (▲) pointing from child to parent
✓Composition uses filled diamond (◆) at the container end
✓Aggregation uses hollow diamond (◇) for weaker ownership
✓Subclasses inherit all parent attributes and methods
✓Composed objects are typically created and managed by the container
📌 Examples
1Vehicle-Car-Motorcycle inheritance hierarchy
2Car composed of Engine and Transmission
3Department aggregates Employees
4Library composed of Books and Shelves