Company Wise Interview Questions And Answers
About Lesson
 Can you explain the difference between aggregation and composition in object-oriented programming? Please provide examples of when you would use each.

  Answer :

In object-oriented programming (OOP), aggregation and composition are both types of relationships that can exist between objects, and they describe how objects are related or how one object “contains” another. They differ primarily in the strength of the relationship between the objects.  

 

1. Aggregation (Has-a relationship):

 

  • Definition: Aggregation represents a “has-a” relationship between objects , where one object contains or is composed of other objects, but the contained objects can exist independently of the container object.
  • Characteristics:
    • The contained objects can exist independently of the container.
    • The container and the contained objects can have separate lifecycles.
    • Aggregation is considered a loose form of association.

 

  • Example: Let’s say we have a Department and Employee class. A department can have employees, but an employee can exist without being in a department. This is an example of aggregation.

class Employee {
    private String name;
    // Constructor, getters, setters...
}

class Department {
    private String departmentName;
    private List employees;  // Employees can exist independently of Department
    // Constructor, getters, setters...
}

 

  • In this example, Employee objects can exist even if they are not assigned to a Department. The relationship between Department and Employee is an aggregation because the Employee can exist independently.
     

 

2. Composition (Strong Has-a relationship):

 

  • Definition: Composition is a stronger form of aggregation, where one object is part of another object, and the lifetime of the contained objects is strictly tied to the container object. If the container object is destroyed, the contained objects will also be destroyed.
  • Characteristics:
    • The contained objects cannot exist without the container object.
    • The lifecycle of the contained objects is bound to the container object.
    • Composition is considered a stronger or more dependent relationship than aggregation.

 

  • Example: Let’s consider the relationship between a House and Room. A room cannot exist without a house, and if the house is destroyed, the rooms will also cease to exist. This is an example of composition.
    java
    
    class Room {
        private String roomName;
        // Constructor, getters, setters...
    }
    
    class House {
        private List rooms;  // Rooms cannot exist without a House
    
        public House() {
            rooms = new ArrayList<>();
            // Initialize rooms here
        }
    }
    
    

    In this case, Room objects cannot exist without the House object. If the House is destroyed, the Room objects are also destroyed. This relationship is an example of composition.