Junior — Middle
How is object creation achieved when using composition?
sobes.tech AI
Answer from AI
When using composition, an object is created by including other objects that implement the necessary functions. The main ways to create objects through composition:
- Via constructor: Dependency injection through constructor parameters.
class Engine {
fun start() = println("Engine started")
}
class Car(private val engine: Engine) {
fun drive() {
engine.start()
println("Car is driving")
}
}
val engine = Engine()
val car = Car(engine)
-
Via setters or methods: Objects are passed through special methods or setters after creation.
-
Via factories or DI containers: Creation and dependency injection are managed by an external component.
Thus, composition is built by including objects into other objects, which increases flexibility and reusability of the code.