Aggregation Vs Composition
Aggregation:Aggregation is a relationship between classes which share "has-a" relationship. Aggregation can be defined as a "Whole-Part" relationship where part of the whole can exist without a whole. Ex: Person has an address. The address will exist even when the person doesn't.
Implementation
example for Aggregation:
package com.visionjava; public class Address { private String apartmentNumber; public String getApartmentNumber() { return apartmentNumber; } public void setApartmentNumber(String apartmentNumber) { this.apartmentNumber = apartmentNumber; } } package com.visionjava; import com.visionjava.Address; public class Person { private Address homeAddress; public Address getHomeAddress() { return homeAddress; } public void setHomeAddress(Address homeAddress) { this.homeAddress = homeAddress; } public static void main(String[] args){ Address homeAddress = new Address(); Person person = new Person(); person.setHomeAddress(homeAddress); } }
As shown above, the address object is created and
provided to person object. Thus, address object will remain
even when person object doesn't.
Composition:
Composition is a relationship between classes
which share "has-a" relationship. Composition can
be defined as a "Whole-Part" relationship where
part of the whole cannot exist without a whole. Ex: House has
a dining room. Dining room cannot exist without the
house.
Implementation
example for Composition:
package com.visionjava; public class LivingRoom { private double height; private double width; public double getWidth() { return width; } public void setWidth(double width) { this.width = width; } public double getHeight() { return height; } public void setHeight(double height) { this.height = height; } } package com.visionjava; public class House { private int noOfRooms; private LivingRoom living = new LivingRoom(); public int getNoOfRooms() { return noOfRooms; } public void setNoOfRooms(int noOfRooms) { this.noOfRooms = noOfRooms; } public LivingRoom getLiving() { return living; } public static void main(String[] args) { House house = new House(); LivingRoom livingRoom = house.getLiving(); } }
The LivingRoom object is created
within the House and it cannot exist without the existence of
the House Object.
That's It! |

