I’m confused between aggregation and containment. I’m wondering if the following represent an aggregation or containment?
class Auto
{
private string model;
private int speed;
class AutoCustomer
{
public string LastName;
public string Address;
public DateTime DateOfPurchase;
}
}
3
The way to understand aggregation versus containment is association versus ownership. Does a car “have” an engine? Yes, it wouldn’t be a car without it (in most situations). Does a fruit bowl “have” fruit? Yes; even if there are currently zero fruit in the bowl.
Does a car “have” a customer? No. The dealership “has” a customer—maybe—and the dealership “has” cars. The dealership may wish to associate a customer with a car they’re interested in, but the car doesn’t own that customer.
A good litmus test for aggregation vs. composition is asking yourself if you would delete the child-object when you delete the parent-object.
When you don’t need the Auto anymore, do you still need the AutoCustomer it references? When you do, you have a case of aggregation. When you don’t need it, you have a case of composition.
If your class Auto
is going to have a reference to the class AutoCustomer
, then this represents an example of Aggregation, since the Auto
class doesnt OWN the AutoCustomer
instance.
But it is sketchy.. since the data members of AutoCustomer
are so specific that it might imply ownership after all, which means its just vanilla composition.