Difference between Aggregation and Composition in Java
What is Aggregation?
Before we start discussing Aggregation, we have to know some general information about our classes in java. Generally we have two members in our classes , the first member are fields which we use to store data so any area that we use to store data or any variable that we use to store data that's we call a lot so example we have a student one of our fields could be the student name or the student ID which are usually in a primitive data type , the other kind of members we have in our classes and we use methods to perform operations for example to calculate the GPA for that student or to get their name or their ID now our fields do not have to be primitive data types we can have a different kind of fields which is an object of another class if you have one of your fields as an object of another class in that case we have an aggregation relationship between these two classes so when you have a thing of another course in your class in that case you have an aggregation relationship between these two classesso generally to know that you have an aggregation relationship you will have a has a connection between these objects so now let's see an example.
Course |
-courseName: String -Instructor: Instructor -textBook: TextBook |
+Course(name:String,Instruc:Instructor,text:TextBook) +getName():String +getInstructor():Instructor +getTextBook():TextBook +toString():String |
Instructor |
-lastName:String -firstName: String -officeNumber: string |
+Instructor(Iname:String,fname:String,office:String) +Instructor(object2:Instructor) +set(Iname:String,fname:String,office:String)void +toString():String |
TextBook |
-title: String -author: String -publisher: String |
+TextBook(title:String,author :String,publisher:String) +TextBook(object2:TextBook) +set(title:String,author:String,publisher:String):void +toString():String |
Explanation:- In the above example, we have a course class and our fields; we have the course name, which is a string. The instructor, an object of the class instructor and the textbook, is an object of the class textbook, so the course class has an instructor, and a course class has a textbook, and that's what we call an aggregation relationship. Now we will see in the UML diagram the type that contains objects of another kind, above we have an arrow shape, which indicates that we have an aggregation relation between these classes, so the course class has an instructor, it has an object of another class, and it also has another thing of that class textbook, so it has a textbook, so we have an aggregation relationship between the course and the instructor, and we have an aggregation relationship between the system and Book. Now we have another example.
package com. shukri;
public class Employee {
private int id;
private String name;
public Employee () {
}
public Employee (int id, String name) {
this.id = id;
this.name=name;
}
public int getId(){
return this.id;
}
public String getName() {
return this. name;
}
public void setId(int id) {
this.id=id;
}
public void setName( String name) {
this.name= Name;
}
Explanation: In the above program, we have an employee, so here we will create a class called employee which I will be storing information about the employee in there; now, here, we want to keep the ID of that employee. We must remember that the instance variable has to be private, so a confidential integer ID, and then we will also store their name, so a private string keeping their name now for each one of them; we will create a getter and a setter. Hence, a public integer gets an ID, and that will be our getter for the ID. We are returning this dot ID the same thing for the name, so I will create a getter for the name public string to get a name that will bear this dot name. We can also create a setter for each one of these objects or these variables so public void, and we are setting the ID so set ID. We will be taking that ID as a parameter for that Method. We are developing this dot ID equal to the ID we pass for that Method. The same thing for the name public void set name, and we are taking the name as a parameter, so string name and we are setting this dot name to be equal to the names we passed as a parameter. We also create a constructor here so the Constructor will have the same name as a class or public employee. This is my default constructor that does not take any parameters and leaves it empty for here, create another constructor that exposes these variables so public employee, and it will take an integer that represents the ID and a string that represents the name, we will set these value, so this dot ID equals ID. Then this dot name equals the name we passed when we created that project. Now, nothing new we are just starting the ID and the string. Now the series is considered a class, so we also have an aggregation relationship here, so the name is an object of the string class so that the employee class has a string. Hence, we have a has a connection here.
What is Composition?
Java uses the composition layout approach to implement has-a connection. Composition allows us to reuse code in the same way that Java inheritance does. The composition is accomplished by utilizing an instance variable that references many other objects. It is considered a composition when one item contains another, and the enclosed Object cannot exist without the other. To put it another way, design refers to a referencing between two or more classes that employ instance variables, and an instance must be constructed before it is utilized.
The following are some advantages of employing composition:
- Program reuse is made possible by composition.
- Java does not allow for multiple inheritances. However, composition enables us to do so.
- A class is more testable when it is composed.
- Through using composition, we have the flexibility to swap out a composite class's functionality with a more efficient and effective one.
- Composition allows us to dynamically alter the behaviour of your programme by changing the component objects at execution.
Do keep in mind the following important Java compositional points:
- It denotes a connection of having.
- These entities are interdependent in their makeup.
- The composed item cannot exist without another entity when there is a composition between two entities. For instance, a library may stock many books on related or unrelated topics. Therefore, all the books in that particular Library will be lost if destroyed.This is because a library is necessary for books to exist.
- Utilizing an instance variable that makes references to particular other objects, the composition is accomplished.
- The composition must take precedence over the inheritance.
Furthermore, go to the graphic underneath to obtain a rough idea of how aggregate operates. Take the real-time library system as an example to properly appreciate how composting works.
Example from Real Life: Library System
Let's use books and libraries as an example to understand java composition better. In this example, we construct two classes, one called Library, which has a connection to the collection of books, and one called Book, which has member functions like creator and subtitle. A library may contain numerous books oneither identical or distinct topics. Therefore, all the books in that List or Library will be destroyed if demolished. i.e., without the need for a library, books would not exist. The composition of the interaction between both the libraries and the books.
// Concept of components illustrated in java program
// Importing all the required classes,
import java.io.*;
import java.util.*;
// Class number 1
// Helper class
// Bookss class
class Bookss {
// instance variable of the class
public String Title;
public String Author;
// Parameterized Constructor of the class
Bookss(String Title, String Author)
{
// this keyword refers to the current calling Object
this.Title = Title;
this.Author = Author;
}
}
// Class number 2
// Helping class
// Library class containing all the List of Booksss.
class Library {
// Referring to the List of books
private final List <Bookss>Booksss;
//Constructor of this class
Library(List<Bookss>Booksss)
{
// this keyword refers to currently calling Object
this.Booksss = Booksss;
}
//Method of the class
// Getting the List of Booksss
public List<Bookss>get_List_Of_Booksss_In_Library()
{
return Booksss;
}
}
// Class number 3
// Main class
class GFG {
// Main Method of the class
public static void main(String[] args)
{
//Object is created of class number 1, which is Bookss class
// inside main() method
Bookss b
= new Bookss("Fluent Python", "Luciano Ramalho");
Bookss b1
= new Bookss("Rust for Rustaceans", "Jon Gjengset");
Bookss b2 = new Bookss("Carbon Programming",
"K.j.Bricknell");
// Creating the List which contains the
// number of Bookss.
List<Bookss>Bookss = new ArrayList<Bookss>();
// Adding Bookss to List object
// using standard add() method
Bookss.add(b);
Bookss.add(b1);
Bookss.add(b2);
//Object is being created for class number 2
Library library = new Library(Bookss);
//Method calling of class number 2 and storing List of Booksss in List
// Here List has been declared of type books which is user-define
List<Bookss>Booksss = library.get_List_Of_Booksss_In_Library();
// Iteration over each loop
for (Bookssbks :Booksss) {
// Printing and displaying the Title and Author of respective
// Booksss inside a List object
System. out.println("Title : " + bks.Title
+ " and "
+ " Author : " + bks.Author);
}
}
}
Difference between Aggregation and Composition
Aggregation | Composition |
1. Aggregation is the combination of two objects that establishes the "has-a" relationship. | 1.Composition is a particular kind of Aggregation that implies owning. |
2. With Aggregation, individual objects can still be included in a program's scope. | 2.In a relationship of composition, two objects are necessary for the system to continue to exist. |
3. Connected items in Aggregation are independent of one another. | 3.During composition, items are interdependent or strongly connected. |
4. When we remove the parent item in Aggregation, the child object will remain in the system. For instance, if we take a car's wheels off, the vehicle can still run smoothly with a different spin. | 4. If we remove a parent object from a composite, the childitem is also removed. For instance, if we draw a directory, all of its contents are destroyed. |
5. We use a natural diamond to indicate it. | 5.We use an empty diamond to symbolize it. |
6. Child objects in Aggregation do not have a lifespan. | 6.Child items have such a lifespan in composition. |
7. If we destroy a component in Aggregation, its members will never be affected. | 7. Having a class has an impact on the item that contains the type. |