-->

17. Aggregation In Java

Inheritance in Java: Previous                                          Next: Command Line argument in Java       

Aggregation In Java

Aggregation is a type of HAS-A relationship. Aggregation represents a type of relationship between two objects in which one contain the other’s reference. Two objects can exist independently. If one is deleted other can still exist.

Aggregation in real world:

Let us take the example: A room has a chair. Here room object contain the chair object. Both room and chair exist independently.

Example:

/**
 * This is used to show simple aggregation example.
 * @author javawithease
 */
class Chair{
      public void show(){
            System.out.println("show chair details.");
      }
}
 
public class RoomTest {
      public static void main(String args[]){
            //Chair class object in RoomTest class
            Chair obj = new Chair();
            obj.show();
      }
}

Output:

show chair details.
Note: Aggregation is mainly used for code re-usability.

Inheritance In Java: Previous                                          Next: Command Line Argument In Java