Aggregation vs Composition


Differences between aggregation and composition include the following: In the following example, in case of aggregation, the Car performs its functions through an Engine, but the Engine is not always an internal part of the Car. An engine can be swapped out or even can be removed from the car. That’s why we make the Engine type field non-final.

(Aggregation) shell> java AvsC         ⇒   Output:

(Composition) shell> java AvsC        ⇒   Output:

   
AvsC.java (aggregation vs composition example)
// Java program to show the difference between aggregation and composition
// Engine class is used by car, so the class Car will have a field of Engine type.
class AvsC {
  public static void main ( String[ ] args ) {
    // Making an engine by creating an instance of Engine class
    Engine engine1 = new Engine( args[0] );
    Engine engine2 = new Engine( args[1] );

    // Making a car with engine, so we are passing an engine
    // instance as an argument while creating instace of Car
    Car car1 = new Car( args[2], engine1 );
    Car car2 = new Car( args[2], engine2 );
    car2.move( engine1 );
  }
}
Engine.java
class Engine {
  String name;
  Engine( String name ) { this.name = name; }

  // Starting an engine
  public void work( ) { System.out.println( this.name ); } 	
}
Car.java
final class Car { 
  String name;
  /*-------------------------------------------------*
   * For a car to move, it needs to have a engine.   *
   * Have to comment out either one of the following *
   * two commands.                                   *
   *-------------------------------------------------*/ 
  private Engine engine;          // Aggregation
  private final Engine engine;    // Composition 
	
  Car( String name, Engine engine ) {
    this.name   = name;
    this.engine = engine;
  }

  // Car starts moving by starting engine. 
  public void move( Engine engine ) { 
    if ( engine != null ) { 
      this.engine = engine;
      System.out.print( this.name + " " + enging.name ); 
    } 
  }
}




      “I’m not young enough to know everything.”    
      ― J.M. Barrie, The Admirable Crichton