What is a composition relationship between two objects?

  • Read
  • Discuss
  • View Discussion

    Improve Article

    Save Article

    Like Article

    Association is a relation between two separate classes which establishes through their Objects. Association can be one-to-one, one-to-many, many-to-one, many-to-many. In Object-Oriented programming, an Object communicates to another object to use functionality and services provided by that object. Composition and Aggregation are the two forms of association. 

    What is a composition relationship between two objects?

    Example:

    import java.io.*;

    class Bank {

        private String name;

          private Set<Employee> employees;

        Bank(String name)

        {

            this.name = name;

        }

        public String getBankName()

        {

            return this.name;

        }

          public setEmployees(Set<Employee> employees){

            this.employees = employees;

        }

      public getEmployees(Set<Employee> employees){

            return this.employees;

        }

    }

    class Employee {

        private String name;

        Employee(String name)

        {

            this.name = name;

        }

        public String getEmployeeName()

        {

            return this.name;

        }

    }

    class GFG {

        public static void main(String[] args)

        {

            Bank bank = new Bank("ICICI");

            Employee emp = new Employee("Ridhi");

            Set<Employee> employees = new HashSet<>();

              employees.add(emp);

              bank.setEmployees(employees);

            System.out.println(bank.getEmployees()+"are belongs to bank"+bank.getBankName());

        }

    }

    OutputRidhi is employee of ICICI

    Output Explanation: In the above example, two separate classes Bank and Employee are associated through their Objects. Bank can have many employees, So it is a one-to-many relationship. 

    What is a composition relationship between two objects?

    Aggregation

    It is a special form of Association where:  

    • It represents Has-A’s relationship.
    • It is a unidirectional association i.e. a one-way relationship. For example, a department can have students but vice versa is not possible and thus unidirectional in nature.
    • In Aggregation, both the entries can survive individually which means ending one entity will not affect the other entity.

    What is a composition relationship between two objects?

    Aggregation

    Example

    import java.io.*;

    import java.util.*;

    class Student {

        String name;

        int id;

        String dept;

        Student(String name, int id, String dept)

        {

            this.name = name;

            this.id = id;

            this.dept = dept;

        }

    }

    class Department {

        String name;

        private List<Student> students;

        Department(String name, List<Student> students)

        {

            this.name = name;

            this.students = students;

        }

        public List<Student> getStudents()

        {

            return students;

        }

    }

    class Institute {

        String instituteName;

        private List<Department> departments;

        Institute(String instituteName,List<Department> departments)

        {

            this.instituteName = instituteName;

            this.departments = departments;

        }

        public int getTotalStudentsInInstitute()

        {

            int noOfStudents = 0;

            List<Student> students;

            for (Department dept : departments) {

                students = dept.getStudents();

                for (Student s : students) {

                    noOfStudents++;

                }

            }

            return noOfStudents;

        }

    }

    class GFG {

        public static void main(String[] args)

        {

            Student s1 = new Student("Mia", 1, "CSE");

            Student s2 = new Student("Priya", 2, "CSE");

            Student s3 = new Student("John", 1, "EE");

            Student s4 = new Student("Rahul", 2, "EE");

            List<Student> cse_students = new ArrayList<Student>();

            cse_students.add(s1);

            cse_students.add(s2);

            List<Student> ee_students

                = new ArrayList<Student>();

            ee_students.add(s3);

            ee_students.add(s4);

            Department CSE = new Department("CSE", cse_students);

            Department EE = new Department("EE", ee_students);

            List<Department> departments = new ArrayList<Department>();

            departments.add(CSE);

            departments.add(EE);

            Institute institute = new Institute("BITS", departments);

            System.out.print("Total students in institute: ");

            System.out.print(institute.getTotalStudentsInInstitute());

        }

    }

    OutputTotal students in institute: 4

    Output Explanation: In this example, there is an Institute which has no. of departments like CSE, EE. Every department has no. of students. So, we make an Institute class that has a reference to Object or no. of Objects (i.e. List of Objects) of the Department class. That means Institute class is associated with Department class through its Object(s). And Department class has also a reference to Object or Objects (i.e. List of Objects) of the Student class means it is associated with the Student class through its Object(s). 

    It represents a Has-A relationship. In the above example: Student Has-A name. Student Has-A ID. Student Has-A Dept. Department Has-A Students as depicted from the below media. 
     

    What is a composition relationship between two objects?

    When do we use Aggregation ?? 
    Code reuse is best achieved by aggregation.  

    Concept 3: Composition 

    What is a composition relationship between two objects?

    Composition

    Composition is a restricted form of Aggregation in which two entities are highly dependent on each other.  

    • It represents part-of relationship.
    • In composition, both entities are dependent on each other.
    • When there is a composition between two entities, the composed object cannot exist without the other entity.

    Example Library

    import java.io.*;

    import java.util.*;

    class Book {

        public String title;

        public String author;

        Book(String title, String author)

        {

            this.title = title;

            this.author = author;

        }

    }

    class Library {

        private final List<Book> books;

        Library(List<Book> books)

        {

            this.books = books;

        }

        public List<Book> getTotalBooksInLibrary()

        {

            return books;

        }

    }

    class GFG {

        public static void main(String[] args)

        {

            Book b1

                = new Book("EffectiveJ Java", "Joshua Bloch");

            Book b2

                = new Book("Thinking in Java", "Bruce Eckel");

            Book b3 = new Book("Java: The Complete Reference",

                               "Herbert Schildt");

            List<Book> books = new ArrayList<Book>();

            books.add(b1);

            books.add(b2);

            books.add(b3);

            Library library = new Library(books);

            List<Book> bks = library.getTotalBooksInLibrary();

            for (Book bk : bks) {

                System.out.println("Title : " + bk.title

                                   + " and "

                                   + " Author : " + bk.author);

            }

        }

    }

    OutputTitle : EffectiveJ Java and Author : Joshua Bloch Title : Thinking in Java and Author : Bruce Eckel Title : Java: The Complete Reference and Author : Herbert Schildt

    Output explanation: In the above example, a library can have no. of books on the same or different subjects. So, If Library gets destroyed then All books within that particular library will be destroyed. i.e. books can not exist without libraries. That’s why it is composition.  Book is Part-of Library.

    Aggregation vs Composition 

    1. Dependency: Aggregation implies a relationship where the child can exist independently of the parent. For example, Bank and Employee, delete the Bank and the Employee still exist. whereas Composition implies a relationship where the child cannot exist independent of the parent. Example: Human and heart, heart don’t exist separate to a Human

    2. Type of Relationship: Aggregation relation is “has-a” and composition is “part-of” relation.

    3. Type of association: Composition is a strong Association whereas Aggregation is a weak Association.

    Example:

    import java.io.*;

    class Engine {

        public void work()

        {

            System.out.println(

                "Engine of car has been started ");

        }

    }

    final class Car {

        private final Engine engine;

        Car(Engine engine)

        {

            this.engine = engine;

        }

        public void move()

        {

            {

                engine.work();

                System.out.println("Car is moving ");

            }

        }

    }

    class GFG {

        public static void main(String[] args)

        {

            Engine engine = new Engine();

            Car car = new Car(engine);

            car.move();

        }

    }

    OutputEngine of car has been started Car is moving

    In case of aggregation, the Car also performs its functions through an Engine. but the Engine is not always an internal part of the Car. An engine can be swapped out or even can be removed from the car. That’s why we make The Engine type field non-final.

    This article is contributed by Nitsdheerendra. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to . See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.