Composition and aggregation
Classes and objects can be related to each other. Inheritance describes an "IS A" relationship. A lion IS AN animal. This relationship is easily expressed using inheritance, where Animal
would be the parent class and Lion
would be the child.
But not every relationship in the world is properly described this way. For example, a keyboard definitely has some relationship with a computer, but it isn't a computer. Hands have some relationship with a person, but they are not a person. These cases represent a different type of relationship — not "IS A", but "HAS A". Hands are not a person, but a person HAS hands.
A keyboard is not a computer, but a computer HAS A keyboard. "HAS A" relationships can be described in code using composition and aggregation. The difference between these concepts lies in the "strictness" of the relationships.
Let's take a simple example:
- We have a
Car
. - Every car has an engine. Additionally, every car can carry passengers.
What is the fundamental difference between the Engine engine
and Passenger[] passengers
fields? If passenger A
is sitting inside a car, that doesn't mean that passengers B
and C
cannot also be in the car.
One car can accommodate multiple passengers. What's more, all the passengers may get out of the car, yet it will continue to function smoothly. The relationship between the Car
class and the Passenger[] passengers
array is less strict. It is called aggregation.
Here's a good article on this topic: Relationships between classes (objects).
It provides another good example of aggregation. Let's say we have a Student
class that represents a student, and a StudentGroup
that represents a group of students. A student can be a member of a physics club, a Star Wars student fan club, or a comedy club.
Composition is a stricter type of relationship. When using composition, an object has another object, but it cannot belong to another object of the same type. The simplest example is a car engine. If a car has an engine, then that engine cannot belong to another car. As you can see, that relationship is much stricter than that of Car
and Passengers
.
GO TO FULL VERSION