Association, Composition and Aggregation in Java

Learn via video course
FREE
View all courses
Java Course - Mastering the Fundamentals
Java Course - Mastering the Fundamentals
by Tarun Luthra
1000
5
Start Learning
Java Course - Mastering the Fundamentals
Java Course - Mastering the Fundamentals
by Tarun Luthra
1000
5
Start Learning
Topics Covered

Introduction

Relationships between classes are crucial in object-oriented programming. Just as the concepts like classes and objects in object-oriented programming are built to model real-world entities, the relationships between classes in object-oriented programming are built to model the relationships between real-world entities, that these classes represent.

In a way, almost everything that we see in the real world can be viewed as a bunch of objects and the relationships/associations between them.

Classes as individual entities( without any relations between them ) are impractical in object-oriented programming because then we would not be able to model the relationships that exist between real-life entities.

A student is called a student because he studies in a school/college. Here both student and college entities can be modeled as two individual classes with a relation of client-provider (wherein college “provides” education to the student) between them. Similarly, there would be no concept of the employee in real life without the existence of an organization that employs individuals, thus an organization is associated with an employee(here the relation is ‘employment’).

Here the Employee and Organization can be modeled as two distinct classes in OOPS with a relation of employment. So understanding how these associations work in object-oriented programming is something every programmer must be aware of, which we shall cover in the further sections of this article.

Association in Java

Association, in general terms, refers to the relationship between any two entities. Association in java is the relationship that can be established between any two classes. These relationships can be of four types:

  1. One-to-One relation

  2. One-to-many relation

  3. Many-to-one relation

  4. Many-to-many relation

To illustrate, let’s take two classes, Professor class, and Department class. Below are the type of relationships/associations that can be possible between them

  • One professor can only be assigned to work in one department. This forms a one-to-one association between the two classes.
  • One professor can be assigned to work in multiple departments. This is a one-to-many association between the two classes.
  • Multiple professors can be assigned to work in one department. This forms a many-to-one association between the two classes.
  • Multiple professors can be assigned to work in multiple departments. This is the many-to-many association between the two classes.

types of association in java These associations in java help the objects of one class to communicate with the objects of the other class.

  • So one object will be able to access the data of another object. For example, A professor entity modeled as an object would be able to access/know the names of all the departments he works at. And a department object can be able to access/know the names/details of all the professors that work in it.
  • Functionality/Services of one object can be accessible to another object. For example, A professor who is trying to enroll in a department can be able to verify whether a department he wants to join has a vacancy. This service(programmatic method/function) to find whether there’s a departmental vacancy can be provided by the Department class which the Professor class can access.

Example program to illustrate one-to-many Association between Department class and Professor class in Java:

Output:

The program is quite simple and straightforward. Below is a detailed explanation of how this works:

  • The program has three classes
    • Main: Where objects are created and actual program functionality is written
    • Professor: Has the variables and methods related to professor class
    • Department: Has the variables and methods related to department class
  • In the Professor Class, We have defined a variable name to store the name of the professor, and we wrote a constructor Professor() that assigns the name of the professor during object creation and a method getName() to fetch the name of the professor.
  • In the Department Class, we have defined a variable name to store the name of the department and a list of staff to store the list of Professor objects( professors that are working in the department ). We wrote a constructor Department() that assigns the name of the department during object creation and three methods. One is getName()to fetch the name of the department. Two is setStaff() to store the list of staff(professor) objects and Three is getStaff() to fetch the list of staff/professor names (professors that are working in the department)
  • In Main class we wrote the implementation
    • Created two objects for Professor class and one object for Department class
    • Next, create a list to store the objects of type Professor,
    • Add the two newly created objects of type Professor to the list. The objects were assigned names “Arun Kumar” & “Rahul Yadav” at their time of creation.
    • The department name is assigned as “CSE”
    • Add the created staff list to CSE department using setStaff() method;
    • Display the stored variables of department name and the list of names of department staff as output.

The classes Professor and Department are meaningfully interacting with each other, which determines their association. And the relation type here is one-to-many, as one department is related to multiple professors.

Forms of Association in Java

Before we dive into the forms of Association in java, let us briefly explore the types of object relationships that can exist in OOPs. There can be two types of relationships in OOPs:

  • IS-A
  • HAS-A

1. IS-A (Inheritance)

The IS-A relationship is nothing but Inheritance. The relationships that can be established between classes using the concept of inheritance are called IS-A relations.

Ex: A parrot is-a Bird. Here Bird is a base class, and Parrot is a derived class, Parrot class inherits all the properties and attributes & methods (other than those that are private) of base class Bird, thus establishing inheritance(IS-A) relation between the two classes.

The HAS-A association on the other hand is where the Instance variables of a class refer to objects of another class. In other words, one class stores the objects of another class as its instance variables thereby establishing a HAS-A association between the two classes.

2. HAS-A (association)

Note: The example program for the association we have discussed in the above section is a HAS-A association.Because Department class is storing the objects of Professor class as its instance variable staff ( the Listwhich is storing a list of Professors class objects). And a Department class object can access these stored Professor objects to store/retrieve information from Professor Class, thereby creating an association between the two classes.

There are two forms of Association that are possible in Java:

a) Aggregation

b) Composition

Aggregation:

Aggregation in java is a form of HAS-A relationship between two classes. It is a relatively more loosely coupled relation than composition in that, although both classes are associated with each other, one can exist without the other independently. So Aggregation in java is also called a weak association. Let us look at a simple aggregation example to understand this better.

Example: Consider the association between a Country class and a Sportsperson class. Here’s how it is defined

  • Country class is defined with a name and other attributes like size, population, capital, etc, and a list of all the Sportspersons that come from it.
  • A Sportsperson class is defined with a name and other attributes like age, height, weight, etc.

In a real-world context, we can infer an association between a country and a sports person that hails from that country. Modeling this relation to OOPs, a Country object has-a list of Sportsperson objects that are related to it. Note that a sportsperson object can exist with his own attributes and methods, alone without the association with the country object. Similarly, a country object can exist independently without any association to a sportsperson object. In, other words both Country and Sportsperson classes are independent although there is an association between them. Hence Aggregation is also known as a weak association.

Another point to note is that here, the Country object has-a Sportsperson object and not the other way around, meaning the Country object instance variables store the Sportsperson objects(This will be clear when we look at the java program in the next section), so the association is one-sided. Thus Aggregation is also known as a unidirectional association.

relation diagram in java aggregation

Program:

Output:

Explanation:

  • A Country class is defined with a variable to store its name and another list of “sportPersons” variable to store the objects of SportPerson.
  • A constructor is defined in Country class to assign the name of the country during object creation
  • Three methods getSportPersons() and setSportPersons() and getName() are defined to set or get the list of sportspersons and to get the name of the country.
  • A SportPerson class is defined with a variable name to store its name and a constructor to assign the name during object creation
  • A method getName() is defined in the SportPerson class to get the name of the sportsperson.
  • The implementation in the Main class is pretty straightforward. Three SportPerson objects are created and a Country object is created. All the three SportPerson objects are added to the newly created list.
  • This is the logical idea behind Aggregation, Sportsperson Class objects can exist independently of the Country class object.
  • if Country object is to be deleted, it has no effect on the SportPerson and vice-versa.
  • Thus Aggregation helps in code reusability. Since classes exist independently, The same classes can be reused to create associations with other classes, without having to modify an existing class, or without causing any issues to existing associations.

Composition:

Composition in java is a form of relation that is more tightly coupled. Composition in java is also called Strong association. This association is also known as Belongs-To association as one class, for all intents and purpose belongs to another class, and exists because of it. In a Composition association, the classes cannot exist independent of each other. If the larger class which holds the objects of the smaller class is removed, it also means logically the smaller class cannot exist. Let us explore this association clearly with an example

Example: The association between College and Student. Below is how it is defined.

  • College class is defined with name and the list of students that are studying in it
  • A Student class is defined with name and the college he is studying at.

Here a student must be studying in at least one college if he is to be called Student. If the college class is removed, Student class cannot exist alone logically, because if a person is not studying in any college then he is not a student.

relation diagram in java composition

Program:

Output:

Explanation:

  • Student class is defined with name and constructor to set the name during object creation
  • A method getName is defined in Student class to get the name of the student
  • College class is defined with name and list of students that are studying in it.
  • A constructor in College class is defined to set the name of the college during the object creation. A method getName is defined to get the name of the college and getStudentList is defined to get the names of the students studying in that college.
  • The method setStudentList is defined, which created three students’ objects inside the College class and assigned them to the college studentList.So here, the Student class objects are created and stored internally in the College class, which creates a tightly bound association between the College and Student classes. Because, if College class is removed, all student objects are removed as well.
  • All the students are to be part of the class, no student can exist independently. And the result is outputted.
  • Note here that no single student can exist without a college, but a college can exist without the student. Student is the dependent class.

Difference between association, aggregation, composition in Java

Association in java is one of the types of relations between classes. It has two forms Aggregation(HAS-A) and Composition(Belongs-to). Aggregation is a relatively weak association, whereas Composition is a strong association. Composition can be called a more restricted form of Aggregation. Aggregation can be called the superset of Composition, since all Compositions can are Aggregations but, not all Aggregations can be called Composition.

difference between association aggregation composition in java

Below are the primary differences between the forms of Association, Composition and Aggregation in java:

AggregationComposition
Weak AssociationStrong Association
Classes in relation can exist independentlyOne class is dependent on Another Independent class. The Dependent class cannot exist independently in the event of the non-existence of an independent class.
One class has-a relationship with another classOnce class belongs-to another class
Helps with code reusability. Since classes exist independently, associations can be reassigned or new associations created without any modifications to the existing class.Code is not that reusable as the association is dependent. Such Associations once established will create a dependency, and these associations cannot be reassigned or new associations like aggregation, etc cannot be created without changing the existing class.

Conclusion

We have reached the end of the article. Below are few real-world examples that you can explore to understand the associations between them:

  • Association between Mobile store and mobiles
  • Association between Car and Engine
  • Association between Library and Books
  • Association between Institute, student and department
  • Association between Building and rooms
  • Association between Band and Musician

Understanding how the different forms of association work give us the ability to write code that is closely relevant and practical in the real world. Please let us know if you face any difficulty in understanding this article. For any queries do reach out to me on Linkedin