What is the difference between association, aggregation, and composition in Java?

Association, Aggregation, and Composition are object-oriented relationships that describe how classes interact with each other. They differ in the strength of their relationship and the dependency between objects.

Key Points: • Association is the broadest relationship where two classes are connected and can use each other. • Aggregation is a weak "has-a" relationship where the child object can exist independently of the parent. • Composition is a strong "has-a" relationship where the child object's lifecycle depends on the parent. • Aggregation and Composition are specialized forms of Association. • Composition provides stronger ownership compared to Aggregation.

Example:

Association: A Teacher teaches Students. Both Teacher and Student can exist independently.

Aggregation: A Department has Professors. If the Department is removed, Professors can still exist.

Composition: A House has Rooms. If the House is destroyed, the Rooms no longer exist as independent entities.

Code Example:

// Association

class Teacher {
}

class Student {
}


// Aggregation

class Professor {
}

class Department {

    private Professor professor;

    public Department(Professor professor) {
        this.professor = professor;
    }
}


// Composition

class Room {
}

class House {

    private Room room = new Room();
}

In the aggregation example, the Professor object can exist without the Department.

In the composition example, the Room is created and owned by the House. If the House is destroyed, the Room loses its existence as part of that House.

Comparison:

Association: • Relationship: Uses-a / Knows-a • Dependency: Low • Lifecycle: Independent

Aggregation: • Relationship: Has-a • Dependency: Weak • Lifecycle: Child can exist without parent

Composition: • Relationship: Strong Has-a • Dependency: Strong • Lifecycle: Child depends on parent

Real-World Examples:

Association: • Doctor and Patient

Aggregation: • Team and Players

Composition: • Car and Engine • House and Rooms

Interview Tip: A concise interview answer is:

"Association is a general relationship between two classes. Aggregation is a weak 'has-a' relationship where the contained object can exist independently of the owner. Composition is a strong 'has-a' relationship where the contained object's lifecycle is tied to the owner object."