×

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

Level order Traversal of a Binary Tree in Java

In Java, a level order traversal of a tree structure is also referred to as the breadth-first traversal of the binary tree. Regarding the subsequent binary tree: Level order traversal is as...

5 minutes read.

Hashing Algorithm in Java

The hashing algorithm is a method that maps data to the fixed-length hash. The Java hash-based algorithm employs a cryptographic mathematical operation. A hash technique or hash function is supposed...

8 minutes read.

Java AWT

Java AWT Java programming is used to develop different types of applications like window-based applications, web applications, Enterprise applications, or mobile applications. For creating standalone applications, Java AWT API is used....

11 minutes read.

Statements in java

What is Statement in java: A statement in java is an instruction that explains what will happen based on the condition. Types of java statements: There are different statements in java Expression statementDeclaration statementControl...

2 minutes read.

Java 9 Tutorial

The Java 9 is most popular release of java programming to make it platform modular. It is used to improve JDK and java implementation security. It provides JAVA SE and...

3 minutes read.

Beautiful Array in Java

In this section, we will be acknowledged about the beautiful array in Java, its characteristics, how it is achieved. What are the types of approaches and what are the tools...

8 minutes read.

Program to Find the Common Elements between two Arrays in Java

In this article, we are going to learn how to find the common elements between two arrays using Java. Here, we use different approaches in Java to find the common...

3 minutes read.

Math fma () method in java

In java, the Math module constitutes of fma () Method in it. This method can be accessed in two ways which can be differentiated by the parameters which are given...

4 minutes read.

Selection Sort in Java

Selection Sort in Java Selection sort is also a simple sorting algorithm that works by repeatedly finding the minimum element from the unsorted portion of the input array, and placing it...

5 minutes read.

Streams in Java

The conventional Java SE 8 version came with many new peculiarities, out of which the most striking of which are assuredly lambda expressions and the method references. Streams and Streams...

14 minutes read.

Jdoodle Java

Everything is instantaneous and fast-paced in the modern world. Online compilers available via the internet are immensely helpful for programmers seeking to learn a new programming language but lacking the...

4 minutes read.

Java Integer valueOf() method

The valueOf() method of Java Integer class returns an Integer object holding the specified int value. The second method returns an Integer object holding the specified String value. The third syntax returns...

2 minutes read.

Even Odd Program in Java

Even Odd Program in Java The number that are completely divisible by 2 are even and the number that leaves remainder are odd numbers. For example, the numbers 2, 0, 4,...

5 minutes read.

Features of Java

The objective of the Java programming language is to provide portability, security, and simplicity. In spite of this, Java has a number of features that makes it a popular language...

5 minutes read.

Minimum Number of Taps to Open to Water a Garden in Java

Problem Statement The issue is that a gardener wants to water a (single-dimensional) garden using the fewest possible tap openings. The goal is to determine the minimum necessary taps to be...

8 minutes read.

Why String in Immutable in Java?

Why String in Immutable in Java Immutable means unchangeable or unmodifiable.  Strings in Java are immutable, it means once a string is created, it cannot be modified or changed. Any change...

2 minutes read.

Collections in Java

Collection framework is one of Java's most powerful subsystems. It is a set of classes and interfaces that is all-the-rage technology for superintending objects and a group of objects. In...

6 minutes read.

FizzBuzz Program in Java

FizzBuzz is a well-known children's game. This game helps children learn division. The FizzBuzz game is becoming a popular programming question, appearing frequently in Core Java interviews. This section will...

3 minutes read.

Java String

Definition A string is a series of characters. Consider an example, "Welcome" is a 7-character string. In Java, String is an unchangeable object. That is, the String is perpetual and cannot be replaced after it is created. This is the tutorial in which you...

4 minutes read.

Moran Numbers in Java

In this article, we will be acknowledged about the moran numbers in Java, how they are formed, what are the approaches to achieve the moran numbers. Moran Number A moran numbers are...

3 minutes read.