Junior — Middle
What is meant by the concept of composition in object-oriented programming?
sobes.tech AI
Answer from AI
In object-oriented programming, composition is a principle where one object contains references to other objects to utilize their functionality. It is a way of building complex objects from simpler ones, where one object 'consists' of others.
Composition differs from inheritance in that instead of extending a class through inheritance, an object includes other objects and delegates some of the work to them. This increases flexibility and code reusability.
Example in Swift:
class Engine {
func start() {
print("Engine started")
}
}
class Car {
private let engine = Engine() // composition: Car contains Engine
func startCar() {
engine.start() // delegate engine start
}
}
let car = Car()
car.startCar() // Outputs: Engine started
Here, the Car class consists of an Engine object and uses its methods without inheriting from it.