Aggregation
Aggregation is a relationship between two classes . That is , an object “has-a” relation with another object.
Lets take an example of the relation between a Person and Address. There is an aggregation relationship between person and Address. Here we can say that a Person class has address object. Person does not manage the lifetime of Address. If Person is destroyed, the Address still exists.
How to represent Aggregation
Aggregation is represented with an unfilled diamond
Below code will help you to understand java implementation of Aggregation.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
package com.j2eereference.aggregation; public class Person{ private String personName; private int age; private Address address; public Person(String personName,int age, Address address) { this.personName= personName; this.age= age; this.address= address; } public String getPersonName() { return personName; } public int getAge() { return age; } public Engine getAddress() { return address; } } |
Now we can create the Address class as below
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
package com.j2eereference.aggregation; public class Address{ private String city; private int zipCode; public Address(String city, int zipCode) { this.city= city; this.zipCode= zipCode; } public String getCity() { return city; } public int getZipCode() { return zipCode; } } |
Here you can notice that
- The address object is created outside and is passed as argument to Person constructor.
- When this person object is destroyed, the address will be still available.
Composition
We can say that composition gives us a ‘part-of‘ relationship.
How to represent Composition
Composition is represented with a filled diamond.
When an object contains the other object and if the contained object cannot exist without the existence of container object, then it is called composition. Lets take an example of Car – Engine and see how can we achieve this composite relation using java code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
package com.j2eereference.composition; public class Car { private String make; private int year; private Engine engine; public Car(String make, int year, int engineCapacity, int engineNumber) { this.make=make; this.year=year; engine = new Engine(engineCapacity, engineNumber); } public String getMake() { return make; } public int getYear() { return year; } public int getEngineNumber() { return engine.getEngineNumber(); } public int getEngineCapacity() { return engine.getEngineCapacity(); } } |
Here you can notice the below points
- We created the engine using parameters passed in Car constructor
- Only the Car instance has access to the engine instance
- When Car instance is destroyed, the engine instance also get destroyed