Core Java

Java Composition Example

In this article, we will see examples of the composition in Java, which is a very important aspect of Programming.

1. Introduction

Association is the relation between two separate classes that establish 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 other Objects to use functionality and services provided by that object. Composition and Aggregation are the two forms of association.

Composition in java is the design technique to implement has-a relationship in classes. We can use java inheritance or Object composition in java for code reuse.

Java composition is achieved by using instance variables that refer to other objects.

The below Java program is to illustrate the concept of Association.

// class bank
class Bank
{
    private String name;

    // bank name
    Bank(String name)
    {
        this.name = name;
    }

    public String getBankName()
    {
        return this.name;
    }
}


// employee class
class Employee
{
    private String name;

    // employee name
    Employee(String name)
    {
        this.name = name;
    }

    public String getEmployeeName()
    {
        return this.name;
    }
}

// Association between both the classes in main method
public class Association {

    public static void main (String[] args)
    {
        Bank bank = new Bank("Axis");
        Employee emp = new Employee("Neha");

        System.out.println(emp.getEmployeeName() +
                " is employee of " + bank.getBankName());
    }

}

The composition is a restricted form of association in which two entities are highly dependent on each other.

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

2. Java Composition Example

 A Person has a Job, let’s see this with a java composition example code.

Job.java

public class Job {
    private String role;
    private long salary;
    private int id;

    public String getRole() {
        return role;
    }
    public void setRole(String role) {
        this.role = role;
    }
    public long getSalary() {
        return salary;
    }
    public void setSalary(long salary) {
        this.salary = salary;
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }

}

Person.java

public class Person {
    //composition has-a relationship
    private Job job;

    public Person(){
        this.job=new Job();
        job.setSalary(1000L);
    }
    public long getSalary() {
        return job.getSalary();
    }

}

Here is a test class for java composition example that uses person object and get its salary.

TestPerson.java

public class TestPerson {
    public static void main(String[] args) {
        Person person = new Person();
        long salary = person.getSalary();

        System.out.println("Salary of person :"+salary);
    }
}

Output:

Salary of person :1000

Lets take another example of Library.

Book.java

class Book
{
    public String title;
    public String author;

    Book(String title, String author)
    {
        this.title = title;
        this.author = author;
    }
}

Library.java

class Library
{
    // reference to refer to list of books.
    private final List books;

    Library (List books)
    {
        this.books = books;
    }

    public List getTotalBooksInLibrary(){

        return books;
    }

}

Test.java

import java.util.ArrayList;
import java.util.List;

class Test
{

    // main method
    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 books = new ArrayList();
        books.add(b1);
        books.add(b2);
        books.add(b3);

        Library library = new Library(books);

        List bks = library.getTotalBooksInLibrary();
        for(Book bk : bks){

            System.out.println("Title : " + bk.title + " and "
                    +" Author : " + bk.author);
        }
    }
}

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

3. Java Composition Benefits

  • If you are looking for code reuse and the relationship between the two classes is has-a then you should use composition rather than inheritance.
  • The benefit of using composition in java is that we can control the visibility of other objects to client classes and reuse only what we need.
  • Also if there is any change in the other class implementation, for example, getSalary returning String, we need to change Person class to accommodate it but client classes don’t need to change.
  • Composition allows the creation of back-end class when it’s needed, for example, we can change the Person getSalary method to initialize the Job object at runtime when required.
  • It is easier to change the class which is implementing composition than inheritance.
  • The composition is done at run time i.e. dynamic binding while Inheritance is done at compile time i.e. static binding.
  • If you want to reuse code and there is no is-a relationship, then use composition. You don’t need to use inheritance for code reuse.
  • If you want polymorphism, but there is no is-a relationship, then use composition with interfaces. You don’t need to use inheritance to get polymorphism.

4 . Download the Source Code

Download
You can download the full source code of this example here: Java Composition Example

Simranjit Singh

Simranjit Singh has graduated from Computer Science Department of the Guru Nanak Dev University of Amritsar, Punjab, India. He also holds a Master degree in Software Engineering from the Birla Institute of Technology & Science of Pilani, Rajasthan, India. He works as a Senior Consultant in the e-commerce sector where he is mainly involved with projects based on Java and Big Data technologies.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button