Composition in Java with Example


< Previous Next >

OOPS Tutorial


1. Overview

In this article, we will learn the important object-oriented concept Composition.
Composition is an association represents a part of a whole relationship where a part cannot exist without a whole.

2. Intent/Definition

Composition is an association represents a part of a whole relationship where a part cannot exist without a whole. If a whole is deleted then all parts are deleted. It has a stronger relationship.

Key Points

  • 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. For example, if order HAS-A line-items, then an order is a whole and line items are parts. If an order is deleted then all corresponding line items for that order should be deleted.
  • Favor Composition over Inheritance.

3. Implementation

Let's take an example of Placing Order. If order HAS-A line-items, then an order is a whole and line items are parts. If an order is deleted then all corresponding line items for that order should be deleted.
Let's implement this example step by step.
Step 1: Create a Product class.
class Product {
    private int id;
    private String name;
    private String description;

    public Product(int id, String name, String description) {
         super();
         this.id = id;
         this.name = name;
         this.description = description;
    }
    public int getId() {
         return id;
    }
    public void setId(int id) {
         this.id = id;
    }
    public String getName() {
         return name;
    }
    public void setName(String name) {
         this.name = name;
    }
    public String getDescription() {
         return description;
    }
    public void setDescription(String description) {
         this.description = description;
    }
    @Override
    public String toString() {
         return "Product [id=" + id + ", name=" + name + ", description=" + description + "]";
    }
}
Step 2: This is LineItem class, which HAS-A aggregation association with Product class.
class LineItem {
    private int id;
    private int quantity;
    private Product p;

    public LineItem(int id, int quantity, Product p) {
         super();
         this.id = id;
         this.quantity = quantity;
         this.p = p;
    }
    public int getId() {
         return id;
    }
    public void setId(int id) {
         this.id = id;
    }
    public int getQuantity() {
         return quantity;
    }
    public void setQuantity(int quantity) {
         this.quantity = quantity;
    }
    public Product getP() {
         return p;
    }
    public void setP(Product p) {
         this.p = p;
    }
    @Override
    public String toString() {
         return "LineItem [id=" + id + ", quantity=" + quantity + ", p=" + p + "]";
    }
}
Step 3: This is Order class, which HAS-A composition association with LineItem class. That means if you delete Order, then associated all LineItem must be deleted.
class Order {
    private int id;
    private String name;
    private List<LineItem> lineItems;

    public Order(int id, String name) {
         super();
         this.id = id;
         this.name = name;
         this.lineItems = new ArrayList<LineItem>();
    }
    public int getId() {
         return id;
    }
    public void setId(int id) {
         this.id = id;
    }
    public String getName() {
         return name;
    }
    public void setName(String name) {
         this.name = name;
    }
 
    @Override
    public String toString() {
         return "Order [id=" + id + ", name=" + name + ", lineItems=" + lineItems + "]";
    }
 
    // Add line item to order
    public void addItem(int id, int quantity, Product p) {
         this.lineItems.add(new LineItem(id, quantity, p));
    }
 
    // Remove line item from order for given item id
    public void removeItemById(int itemId) {
         // TODO - Not implemented yet
    }
}
Step 4: Let's write a test CompositionDemo class to test the above implementation:
public class CompositionDemo {
    public static void main(String[] args) {
         // Create Products
         Product p1 = new Product(1, "Pen", "This is red pen");
         Product p2 = new Product(2, "Pencil", "This is pencil");
         Product p3 = new Product(3, "ColorBox", "This is color box");
        
         // Create Order and Add Line Items
         Order o = new Order(1, "ORD#1");
         o.addItem(1, 2, p1); // Ordered of 2 quantity for p1 product
         o.addItem(2, 1, p2); // Ordered of 1 quantity for p2 product
         o.addItem(3, 5, p3); // Ordered of 5 quantity for p3 product  
         // Print Order detail before deleting 
         System.out.println("Order ---");
         System.out.println(o);
         // Deleting order would also delete associated LineItems   
         o = null;  
    }
}

Related Oops Posts

Top Core Java Tutorials

  1. Java Tutorial for Beginners
  2. 50 Java Keywords
  3. JDBC 4.2 Tutorial
  4. All Java/J2EE Tutorial
  5. Java 8 Tutorial
  6. Java Collections Tutorial
  7. Java Exceptions Tutorial
  8. Java Generics Tutorial
  9. Java 8 Stream API Tutorial
  10. Java Wrapper Classes
  11. Java Arrays Guide
  12. Java Multithreading Tutorial
  13. Java Concurrency Tutorial
  14. Oops Concepts Tutorial
  15. Java String API Guide
  16. Java Reflection API Tutorial
  17. Java I/O Tutorial
  18. Date and Time API Tutorial
  19. JUnit 5 Tutorial
  20. JUnit 4 Tutorial
  21. Java XML Tutorial
  22. Google GSON Tutorial

Top Java EE Tutorials

  1. Spring Security Tutorial
  2. RabbitMQ Tutorial
  3. Hibernate ORM 5
  4. Java Persistence API
  5. Spring Boot 2 Tutorial
  6. Spring Core 5 Tutorial
  7. Spring MVC 5 Tutorial
  8. Spring Data JPA Tutorial
  9. Apache HttpClient Tutorial
  10. Spring Framework 5
  11. Apache Maven Tutorial
  12. JAX-RS Tutorial
  13. Jersey Rest Tutorial

Java Library Tutorials

  1. Java API Guides
  2. Java SQL Package Tutorial
  3. All Java/J2EE Tutorial
  4. Java Lang Package Tutorial
  5. Java Util Package Tutorial
  6. Java Lang Reflect Package Tutorial
  7. Java Time Package Tutorial
  8. Java IO Package Tutorial

Top Java Best Practices

  1. Java Enums and Annotations Best Practices
  2. Java Generics Best Practices
  3. JUnit Framework Best Practices
  4. Java Naming Conventions
  5. Single Responsibility Principle
  6. Liskov's Substitution Principle
  7. Interface Segregation Principle
  8. Dependency Inversion Principle
  9. Open Closed Principle
  10. Oops principles in java
  11. Restful API Best Practices
  12. JSP Best Practices
  13. Guide to JDBC Best Practices
  14. Collection Best Practices
  15. String Best Practices in Java
  16. Exception Handling Best Practices
  17. Synchronization Best Practices
  18. Guide to JDBC Best Practices
  19. Serialization Best Practices

 
The source code of this post is available on GitHub: Object-Oriented Design Guide

Comments