Rhonwen Van Druten
Rhonwen Van Druten

Reputation: 45

Is Aggregation the same as Composition?

Good day,

What is aggregation and what is composition? Are they the same?

As I understand it, is that there are no difference.

According to: [This Website] they do differ in subtle ways. However I do think that they are not on the right track... Let me explain.

In their definition they are saying the following: (I quote)

Aggregation

Implies a relationship where the child can exist independently of the parent.

Composition

Implies a relationship where the child cannot exist independent of the parent.

By saying 'child' and 'parent' implies that there is a 'base class' and a 'derived class'. Meaning that there is in fact an 'is-a' relationship between these two classes. According how I understand relationships is that there cannot be a 'has-a' relationship, since there is already an 'is-a' relationship.

See code below:

public class Animal
{
...
}
public class Reptile : Animal
{
...
}
public class Mammal : Animal
{
...
}
public class Address
{
 ...
}
public class Zoo
{
 private Address address;
 private Mammal mammal;
 private Reptile reptile;
 private string name;

 ...
}

According to the definition the website gave me 'Zoo' is a derived class of Address, Mammal and Reptile, which I strongly disagree since the 'Zoo' class does not inherit anything.

My understanding of Composition and Aggregation is when a class has a, 'has-a' relationship with another class just like the Zoo class have with multiple classes.

If there is a difference please help me to understand it right.

Regards Rhonwen

Upvotes: 1

Views: 368

Answers (1)

JTM
JTM

Reputation: 33

You are correct. Aggregation is creating of an object or class using different stand-alone components from other unrelated classes, whereas composition uses derived parent-child classes to specialise behaviours.

Your Zoo class does not derive from Animal, for instance but uses instances of it. Were you to derive Primate or Dog from Animal and make a MonkeyZoo or DogZoo, you would be dependant on Animal in your new derived Zoo.

Modern OO theory is tending to favour aggregation over composition as too many virtual derivatives can overspecialise and prove confusing - better to compose a class of simple reusable objects and derive them for specialist needs.

https://javarevisited.blogspot.com/2014/02/ifference-between-association-vs-composition-vs-aggregation.html

Upvotes: 1

Related Questions