×

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:

  1. Program reuse is made possible by composition.
  2. Java does not allow for multiple inheritances. However, composition enables us to do so.
  3. A class is more testable when it is composed.
  4. Through using composition, we have the flexibility to swap out a composite class's functionality with a more efficient and effective one.
  5. 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

AggregationComposition
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.

Related Topics

How to compare two dates in different format in Java?

We need to compare two dates frequently when coding. Real-world examples include sorting a list of persons by age or keeping track of students' attendance. To compare two dates, we...

7 minutes read.

Tribonacci series in Java

The Fibonacci series and the Tribonacci sequence are linked. The Fibonacci sequence, each element summates the three preceding terms, is expanded into the Tribonacci series in Java. Through specific examples,...

3 minutes read.

Java Snippets

The term "snippet" refers to a section of code that addresses numerous issues with just a few lines of code. Decreases the number of lines of code and improves programmer...

3 minutes read.

Java Class Syntax

A class is a fundamental building piece in object-oriented programming. It can be characterised as a template that outlines the information and actions connected to the creation of a class....

3 minutes read.

Difference between JIT and JVM in Java

In this tutorial, we will discuss the difference between JIT (Just In Time Compiler) and JVM (Java Virtual Machine) in Java. Before we move to the differences, let's understand what...

4 minutes read.

How to find characters with the maximum number of times in a string java

Problem statement In this problem, users want to find the maximum count of a character from the string and return the character along with its count. Your task is to create...

3 minutes read.

AbstractSet Class in Java

The AbstractSet class is used for the implementation of the Abstract Collection class and interface. It is the part of Collection Frameworks. In the AbstractSet, the implementation is same as the...

3 minutes read.

Java Get Time in UTC

UTC is the abbreviation for Universal Time Coordinated. Before the beginning of UTC, it is mentioned as the Greenwich Mean Time (GMT) but Now it is mentioned as the universal...

4 minutes read.

Java class class

Java Class class instances are an executing Java application's implementation of the classes and interfaces. As well as, every Array is indeed an object that is common for all Arrays...

6 minutes read.

How Many Ways to Create an Object in Java?

As you know, a class is a blueprint for an object, and you can create objects from it. There are several ways to create objects of classes in Java. This...

6 minutes read.

Java Package Keyword

A collection of classes, interfaces, and subpackages in a Java program are referred to as a package. Here, we'll learn in-depth how to make and use user-defined packages. package is a...

6 minutes read.

HttpURLConnection

HttpURLConnection Protocol It is a standard set of rules that allow electronic devices to communicate with each other. The http protocol The http protocol is for data communication, distributing, collaborating, hypermedia information systems, on the World Wide...

5 minutes read.

Singleton Design Pattern in Java

In the singleton pattern, a class that only has one instance and offers a universal point of access is taken into consideration. It can also be defined in another way, a...

4 minutes read.

Java DatagramSocket and Java DatagramPacket

Datagrams TCP/IP style networking specifies a serialized, predictable, and reliable stream of data in the form of a packet. Servers and clients communicate through a reliable channel, such as TCP socket, have a dedicated...

6 minutes read.

Difference between this and super in Java

In this article, you will be very well equipped with the knowledge of this keyword and super keyword in java. You will be able to understand where to implement this...

3 minutes read.

Morris Traversal for Preorder in Java

Without the use of recursion or stacks, we traverse a tree using the Morris algorithm. The linked binary tree is the foundation of the Morris traversal. Preorder Morris Traversal Algorithm The preorder...

3 minutes read.

Special Operators in Java

An operator in Java is a special symbol. It is used to perform operations on two or more variables.  We all know basic operations in Java. There are 8 types...

5 minutes read.

Java Worker Class

What is a Worker? A service which executes Work - flow and Activities is referred to as a Worker. On user-controlled hosts, workers are defined and put into action. The Worker...

3 minutes read.

Java Macros

Macros are additions to the JDK 7 compiler in Java. Compile time macros are added and supported. Macros are Java classes that are instantiated and executed during the compilation process....

2 minutes read.

Skyline Problem in Java

The skyline of a city is the outer edge of the pattern created by all of its structures when viewed from a distance. Return the skyline that these buildings together...

4 minutes read.