Composition
In Java, composition is a design principle that allows you to create complex objects by combining simpler objects or types. It is a way to achieve code reuse without using inheritance. Composition involves creating relationships between classes by having one class contain an instance of another class. This is in contrast to inheritance, where a class can inherit properties and behaviors from another class.
Here's a simple example to illustrate composition in Java:
// Simple class representing an Engine
class Engine {
public void start() {
System.out.println("Engine started");
}
}
// Class representing a Car that uses composition to include an Engine
class Car {
private Engine engine;
public Car(Engine engine) {
this.engine = engine;
}
public void start() {
System.out.println("Car is starting");
engine.start();
}
}
public class CompositionExample {
public static void main(String[] args) {
// Create an Engine instance
Engine carEngine = new Engine();
// Create a Car instance, passing the Engine instance through the constructor
Car myCar = new Car(carEngine);
// Start the car, which internally starts the engine
myCar.start();
}
}In this example:
The
Engineclass has a methodstart()that prints a message indicating the engine is starting.The
Carclass has a composition relationship with theEngineclass. It contains an instance of theEngineclass as a private member variable.The
Carclass also has a methodstart(), which, in addition to printing a message for the car starting, delegates the task of starting the engine to theEngineinstance.
By using composition, you can create modular and flexible code. If you later need to change the behavior of the Engine class, it won't affect the Car class as long as the interface between them remains the same. This is in contrast to inheritance, where changes to a superclass can potentially affect all subclasses.
Example 2
Last updated
Was this helpful?