Junior — Middle
Explain the concept of composition in object-oriented programming.
sobes.tech AI
Answer from AI
Composition in object-oriented programming is a principle where one object contains another object as part of its structure to utilize its functionality.
Unlike inheritance, where a class extends the behavior of a base class, composition allows creating complex objects from simple ones by combining them.
Example:
class Engine {
void start() {
System.out.println("Engine started");
}
}
class Car {
private Engine engine = new Engine();
void startCar() {
engine.start();
System.out.println("Car is running");
}
}
Here, the Car class contains an Engine object and uses its methods, demonstrating composition.