Is it possible to differentiate between composition and aggregation relationship by reading the source code?
I tried to find some patterns and I have listed them below.
I am taking the example from this site just to explain what I assume to be a pattern
COMPOSITION
public class Engine
{
. . .
}
public class Car
{
Engine e = new Engine();
.......
}
AGGREGATION
public class Address
{
. . .
}
public class Person
{
private Address address;
public Person(Address address)
{
this.address = address;
}
. . .
}
I find these patterns to differentiate
COMPOSITION (is a part of )
Defined as a field of a class.
- Example: [Engine e] Engine is defined as a field e of the class Car
Instantiated and assigned within the class.
- Example: [Engine e = new Engine();] Engine is instantiated inside the class
Aggregation (has a)
Defined as a field of a class
- Example: [private Address address;] Address is defined as a field address of the class Person
Instatiated out side the class
- Example: [Address address = new Address();] Address is instatiated outside Person.
Assigned in the constructor by sending the instance as a argument to the constructor.
- Example: [Person person = new Person(address);] The instance of Address is passed as an argument through the constructor and assigned in the constructor of the class Person.
CAN I CONSIDER THESE TO DIFFERENTIATE AGGREGATION AND COMPOSITION RELATION?
ARE THERE MORE CONSTRAINTS THAT ARE USED TO DIFFERENTIATE?