In Java, what are composition and aggregation? Explain the difference. Give examples.
In Java, composition and aggregation are two types of associations that describe relationships between classes. Both concepts are part of object-oriented programming and help in modeling real-world relationships between objects. However, they differ in terms of ownership and lifecycle management.
Definition: Composition is a strong form of association where one class (the container) contains references to one or more objects of another class (the contained). In composition, the contained objects cannot exist independently of the container. If the container is destroyed, the contained objects are also destroyed.
Example:
class Engine {
// Engine properties and methods
}
class Car {
private Engine engine; // Car "has-a" Engine
public Car() {
this.engine = new Engine(); // Car creates its own Engine
}
// Other Car methods
}
In this example, a Car
has an Engine
. The Engine
is created within the Car
class, meaning that if the Car
object is destroyed, the Engine
object will also be destroyed. The Engine
cannot exist without the Car
.
Definition: Aggregation is a weaker form of association where one class (the container) contains references to one or more objects of another class (the contained), but the contained objects can exist independently of the container. If the container is destroyed, the contained objects can still exist.
Example:
class Driver {
// Driver properties and methods
}
class Car {
private Driver driver; // Car "has-a" Driver
public void assignDriver(Driver driver) {
this.driver = driver; // Car can have a Driver assigned
}
// Other Car methods
}
In this example, a Car
can have a Driver
, but the Driver
can exist independently of the Car
. If the Car
object is destroyed, the Driver
object can still exist. The Driver
is not created or owned by the Car
.
Ownership:
Lifecycle:
Example Context:
House
has Rooms
. If the House
is destroyed, the Rooms
are also destroyed.School
has Teachers
. If the School
is closed, the Teachers
can still exist and work elsewhere.Understanding these concepts helps in designing systems that accurately reflect the relationships between different entities in your application.