What is a composition of an object?

View Discussion

Improve Article

Save Article

Like Article

  • Read
  • Discuss
  • View Discussion

    Improve Article

    Save Article

    Like Article

    The composition is a design technique in java to implement a has-a relationship. Java Inheritance is used for code reuse purposes and the same we can do by using composition. The composition is achieved by using an instance variable that refers to other objects. If an object contains the other object and the contained object cannot exist without the existence of that object, then it is called composition. In more specific words composition is a way of describing reference between two or more classes using instance variable and an instance should be created before it is used. 

    What is a composition of an object?

    The benefits of using Composition is as follows: 

    1. Composition allows the reuse of code.
    2. Java doesn’t support multiple inheritances but by using composition we can achieve it.
    3. Composition offers better test-ability of a class.
    4. By using composition, we are flexible enough to replace the implementation of a composed class with a better and improved version.
    5. By using composition, we can also change the member objects at run time, to dynamically change the behaviour of your program.

    Do remember the certain key points of composition in java which are as follows:

    • It represents a has-a 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. For example, A library can have no. of books on the same or different subjects. So, If the Library gets destroyed then All books within that particular library will be destroyed. This is because books can not exist without a library.
    • The composition is achieved by using an instance variable that refers to other objects.
    • We have to favour Composition over Inheritance.

    Now let us finally refer to the below image in order to get a faint hint about the aggregation and to better understand how the composition works, let us take an example of the real-time library system.

    Real-life Example: Library system 

    Let’s understand the composition in Java with the example of books and library. In this example, we create a class Book that contains data members like author, and title and create another class Library that has a reference to refer to the list of books. A library can have no. of books on the same or different subjects. So, If the Library gets destroyed then All books within that particular library will be destroyed. i.e., books can not exist without a library. The relationship between the library and books is composition.

    Implementation:

    Example

    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> getListOfBooksInLibrary()

        {

            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> book = new ArrayList<Book>();

            book.add(b1);

            book.add(b2);

            book.add(b3);

            Library library = new Library(book);

            List<Book> books

                = library.getListOfBooksInLibrary();

            for (Book bk : books) {

                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


    Composition vs Inheritance is one of the frequently asked interview questions. You must have also heard to use Composition over Inheritance.

    Both composition and inheritance are object-oriented programming concepts. They are not tied up with any specific programming language such as Java. Before we compare composition over inheritance programmatically, let’s have a quick definition of them.

    Composition

    Composition is the design technique in object-oriented programming to implement has-a relationship between objects. Composition in java is achieved by using instance variables of other objects. For example, a person who has a Job is implemented like below in java object-oriented programming.

    package com.journaldev.composition; public class Job { // variables, methods etc. } package com.journaldev.composition; public class Person { //composition has-a relationship private Job job; //variables, methods, constructors etc. object-oriented

    Inheritance

    Inheritance is the design technique in object-oriented programming to implement is-a relationship between objects. Inheritance in Java is implemented using the extends keyword. For example, Cat is an Animal relationship in java programming will be implemented like below.

    package com.journaldev.inheritance; public class Animal { // variables, methods etc. } package com.journaldev.inheritance; public class Cat extends Animal{ }

    Composition over Inheritance

    Both composition and inheritance promote code reuse through different approaches. So which one to choose? How to compare composition vs inheritance. You must have heard that in programming you should favor composition over inheritance. Let’s see some of the reasons that will help you in choosing composition vs inheritance.

    1. Inheritance is tightly coupled whereas composition is loosely coupled. Let’s assume we have below classes with inheritance.

      package com.journaldev.java.examples; public class ClassA { public void foo(){ } } class ClassB extends ClassA{ public void bar(){ } }

      For simplicity, we have both the superclass and subclass in a single package. But mostly they will be in the separate codebase. There could be many classes extending the superclass ClassA. A very common example of this situation is extending the Exception class. Now let’s say ClassA implementation is changed like below, a new method bar() is added.

      package com.journaldev.java.examples; public class ClassA { public void foo(){ } public int bar(){ return 0; } }

      As soon as you start using new ClassA implementation, you will get compile time error in ClassB as The return type is incompatible with ClassA.bar(). The solution would be to change either the superclass or the subclass bar() method to make them compatible. If you would have used Composition over inheritance, you will never face this problem. A simple example of ClassB implementation using Composition can be as below.

      class ClassB{ ClassA classA = new ClassA(); public void bar(){ classA.foo(); classA.bar(); } }
    2. There is no access control in inheritance whereas access can be restricted in composition. We expose all the superclass methods to the other classes having access to subclass. So if a new method is introduced or there are security holes in the superclass, subclass becomes vulnerable. Since in composition we choose which methods to use, it’s more secure than inheritance. For example, we can provide ClassA foo() method exposure to other classes using below code in ClassB.

      class ClassB { ClassA classA = new ClassA(); public void foo(){ classA.foo(); } public void bar(){ } }

      This is one of the major advantage of composition over inheritance.

    3. Composition provides flexibility in invocation of methods that is useful with multiple subclass scenario. For example, let’s say we have below inheritance scenario.

      abstract class Abs { abstract void foo(); } public class ClassA extends Abs{ public void foo(){ } } class ClassB extends Abs{ public void foo(){ } } class Test { ClassA a = new ClassA(); ClassB b = new ClassB(); public void test(){ a.foo(); b.foo(); } }

      So what if there are more subclasses, will composition make our code ugly by having one instance for each subclass? No, we can rewrite the Test class like below.

      class Test { Abs obj = null; Test1(Abs o){ this.obj = o; } public void foo(){ this.obj.foo(); } }

      This will give you the flexibility to use any subclass based on the object used in the constructor.

    4. One more benefit of composition over inheritance is testing scope. Unit testing is easy in composition because we know what all methods we are using from another class. We can mock it up for testing whereas in inheritance we depend heavily on superclass and don’t know what all methods of superclass will be used. So we will have to test all the methods of the superclass. This is extra work and we need to do it unnecessarily because of inheritance.

    That’s all for composition vs inheritance. You have got enough reasons to choose composition over inheritance. Use inheritance only when you are sure that superclass will not be changed, otherwise go for composition.

    Join our DigitalOcean community of over a million developers for free! Get help and share knowledge in our Questions & Answers section, find tutorials and tools that will help you grow as a developer and scale your project or business, and subscribe to topics of interest.

    Sign up