aggregation example

The following two tabs change content below.
Prasad Kharkar is a java enthusiast and always keen to explore and learn java technologies. He is SCJP,OCPWCD, OCEJPAD and aspires to be java architect.

Latest posts by Prasad Kharkar (see all)

We know about the association relationship in java, but there are forms of association. we all have read about aggregation relationship and composition relationship in java. This article will deal with aggregation example.

Aggregation Example:

By definition we know that two classes have aggregation relationship when one class has the reference of other class but other class can still exist outside the containing class. 

Now consider two classes. Bike and Engine. We have following assumptions.

  • A bike HAS-A engine
  • An engine can exist without bike. (because we can manufacture engine separately and then mount on the bike)
  • The bike must have an engine

Now we create Bike and Engine classes as below for our aggregation example.



Some points to notice about this aggregation example:


  • Bike HAS-A Engine because we have defined an Engine member variable in Bike
  • using Bike constructor, we are setting the engine to bike.
  • The engine is coming from outside.

Aggregation example below tests this

This prints

Engine object
Engine object
Engine object

Let us see what’s happening in aggregation example

  • Engine engine = new Engine() creates a new Engine object, we are creating it outside bike.
  • We are creating a bike using new Bike(engine);  i.e. passing the outside engine object to Bike constructor.
  • After that we are printing   engine  and bike.getEngine() , they are same objects.
  • Now after setting bike = null; we are printing engine. It still gives same result
  • It means even after we have destroyed bike, its engine still exists.

From above observations we can note that aggregation is a weak association and existence of the object does not depend upon existence of owning object. i.e. Engine still exists without a Bike

I hope this aggregation example helped understand the concept. We will see composition in next article.




Share Button

4 comments for “aggregation example

  1. Rashid
    July 16, 2017 at 5:19 pm

    Sir, Where we use composition in Java program.please reply sir in detail.

Leave a Reply

Your email address will not be published. Required fields are marked *