Composition in Java

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 inheritance. 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 instance should be created before is used. To better understand how the composition works, let’s take the example of Library

Example:

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 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 are composition.

Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to illustrate
// the concept of Composition
import java.io.*;
import java.util.*;
  
// class book
class Book {
  
    public String title;
    public String author;
  
    Book(String title, String author)
    {
  
        this.title = title;
        this.author = author;
    }
}
  
// Libary class contains
// list of books.
class Library {
  
    // reference to refer to list of books.
    private final List<Book> books;
  
    Library(List<Book> books) { this.books = books; }
  
    // Getting total number of books
    public List<Book> getTotalBooksInLibrary()
    {
  
        return books;
    }
}
  
// Driver Code
class GFG {
    public static void main(String[] args)
    {
  
        // Creating the Objects of Book class.
        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");
  
        // Creating the list which contains the
        // no. of books.
        List<Book> book = new ArrayList<Book>();
        book.add(b1);
        book.add(b2);
        book.add(b3);
  
        Library library = new Library(book);
  
        List<Book> books = library.getTotalBooksInLibrary();
        for (Book bk : books) {
  
            System.out.println("Title : " + bk.title
                               + " and "
                               + " Author : " + bk.author);
        }
    }
}

chevron_right


Output

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

Benefits of using Composition: 

  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 behavior of your program.

Key points of Composition in Java

  1. It represents a has-a relationship.
  2. In composition, both the entities are dependent on each other.
  3. 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. i.e., books can not exist without a library.
  4.  The composition is achieved by using an instance variable that refers to other objects. 
  5. We have to favor Composition over Inheritance.

Attention reader! Don’t stop learning now. Get hold of all the important Java and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.