Object Oriented Programming Concepts

Composition and Aggregation

In Object-Oriented Programming (OOP), Composition and Aggregation are two forms of association between objects. Understanding the difference between them is crucial for proper system design and relationship management among objects.

Composition

Composition is a strong "has-a" relationship where the composed object cannot exist independently of the owner.

Composition is like a brain in a human body. The brain exists as long as the body exists.

  • Characteristics:

    • Life Cycle: The life cycle of the composed object is controlled by the owner object.
    • Example: A Person class having a Heart class. The Heart cannot exist without a Person.
  • Example in Java:

    class Person {
        private Heart heart = new Heart();
    
        class Heart {
            void beat() {
                System.out.println("Heart is beating");
            }
        }
    }

Aggregation

Aggregation is a weaker "has-a" relationship where the aggregated object can exist independently of the owner.

Aggregation is like players in a soccer team. Players can join or leave a team without ceasing to exist.

  • Characteristics:

    • Life Cycle: The life cycle of the aggregated object is not tied to the owner object.
    • Example: A Team class having a list of Player objects. Players can exist independently of a Team.
  • Example in Java:

    class Team {
        private List<Player> players;
    
        Team(List<Player> players) {
            this.players = players;
        }
    }
    
    class Player {
        void play() {
            System.out.println("Player is playing");
        }
    }

Understanding Composition and Aggregation helps in designing systems with appropriate object relationships. Composition implies ownership and life cycle dependency, whereas Aggregation allows for independent existence, providing flexibility in the association between objects.

Concept Description Characteristics Example
Composition Strong "has-a" relationship. Component cannot exist independently of the owner. - Life cycle tied to owner
- Owner controls creation and destruction
Person has a Heart. Heart cannot exist without Person.
Aggregation Weaker "has-a" relationship. Component can exist independently of the owner. - Life cycle not tied to owner
- Owner does not control creation and destruction
Team has Players. Players can exist without Team.