Composition


Composition is a restricted form of aggregation in which two entities are highly dependent on each other. In the following example, a library can have a number of books on same or different subjects. So, if a library gets destroyed then all books within that particular library will be destroyed; i.e., book can not exist without library. That’s why it is composition.

Composition.java (a composition example)
// Java program to illustrate the concept of composition 
import java.util.*; 

// Main method 
class Composition {
  public static void main( String[ ] args ) {
    String[ ] titles  = new String[3];
    String[ ] authors = new String[3];
    for ( int i=0, j=0;  j < 3;  i+=2, j++ )
      if ( i < args.length ) {
        titles[j]  = args[i];
        authors[j] = args[i+1];
      }
      else {
        titles[j]  = "";
        authors[j] = "";
      }					  
    // Creating the objects of Book class
    Book b1 = new Book( titles[0], authors[0] );
    Book b2 = new Book( titles[1], authors[1] );
    Book b3 = new Book( titles[2], authors[2] );

    // Creating the list which contains the books
    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 )
      if ( bk.getTitle( ) != "" )
        System.out.println( "Title: " + bk.title + " and "
           + "Author: " + bk.author + "\n" );
  } 
}
Book.java (the Book class)
// Class Book 
class Book { 
  public String title;
  public String author;
  Book( String title, String author ) { 
    this.title  = title; 
    this.author = author; 
  } 
  String getTitle( ) { return this.title; }
}
Library.java (the Library class)
// Libary class contains list of books. 
import java.util.*;

class Library { 
  // Reference to refer to list of books 
  private final List<Book> books; 
  Library ( List<Book> books ) { this.books = books; } 
  public List<Book> getTotalBooksInLibrary( ) { return books; }
}
shell> java Composition

(title)   (author)

(title)   (author)

(title)   (author)