What do you know about class composition?
sobes.tech AI
Answer from AI
Composition is the relationship between classes where one class contains instances of other classes. It is a form of object association where the related object (component) lives and dies together with the containing object.
Distinctive features of composition:
- Strict inclusion: The component is part of the containing object and cannot exist independently.
- Strong dependency: Changes in the containing object often require changes in its components.
- "Part of" relationship: For example, a car has an engine. The engine is part of the car.
Example:
A Car class can contain an instance of the Engine class:
class Engine {
fun start() {
// Start the engine
}
}
class Car {
private val engine = Engine() // Composition
fun drive() {
engine.start()
// Driving logic
}
}
In this example, Engine is a component of Car. The Engine cannot exist without the Car. When the Car object is destroyed, its Engine component also ceases to exist (within the context of this aggregate).
Composition is preferred over inheritance in many cases because it provides greater flexibility and less coupling between classes. It promotes the principle of "program to interfaces, not implementations" and "prefer composition over inheritance."