|
|
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 );
}
}
|
|
class Engine {
String name;
Engine( String name ) { this.name = name; }
// Starting an engine
public void work( ) { System.out.println( this.name ); }
}
|
|
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 );
}
}
}
|