Composition vs Aggregation

Kitchen in House is Composition and Engine in Car is Aggregation


If internal attributes can not exist without Outer Class, that goes to Composition. You can not take Bedroom, Kitchen or Balcony out of any Flat or House.


public class CompositionExample{
  public static void main(String[] args) {
    House house = new House();

class House {
   public Kitchen kitchen;
   public House() {
       kitchen = new Kitchen();

class Kitchen {
   // Kitchen's Attributes

Now imagine, Can we access Kitchen if we set

house = null;

No. It means, the attributes of House (i.e. Kitchen) Class can not exist without its House Class itself.


But you can keep Engine out of any Car and put in any other Car. How?

public class AggregationExample {
   public static void main(String[] args) {
     Car car1 = new Car();
     Engine eng = new Engine();

public class Car {
   private Engine engine;
   //Engine getter/setter;

public class Engine {
   //Engine's attributes

If you notice here even if we set

car1 = null;

We still can access “engine” and put it in another Car


Car car2 = new Car();

The above code examples can be found in GIT .

Hope this clears your doubt on Composition and Aggregation.