Get free ebooK with 50 must do coding Question for Product Based Companies solved
Fill the details & get ebook over email
Thank You!
We have sent the Ebook on 50 Must Do Coding Questions for Product Based Companies Solved over your email. All the best!

Association, Composition, and Aggregation in Java

Last Updated on December 28, 2023 by Ankit Kochar

In the realm of object-oriented programming (OOP), Java provides developers with powerful tools to model relationships between classes. Three essential concepts that define these relationships are Association, Composition, and Aggregation. Understanding these concepts is fundamental to designing robust and maintainable Java applications. Association represents a simple connection between classes, Composition depicts a strong "whole-part" relationship, and Aggregation signifies a more loosely coupled association. This article delves into these concepts, exploring their nuances and providing insights into how they influence the structure and behavior of Java programs.

Association in Java

Association in java is a relationship between two classes in Java where an object of one class is related to an object of another class. In association, the objects of the classes have a reference to each other, but they can also exist independently.

Code Implementation

import java.util.*;

class Product{
    private String name;
    private double price;
    
    
    Product(String name, double price){
        this.name = name;
        this.price = price;
    }
    
    double getPrice(){
        return price;
    }
}
class Basket {
    private List<Product> products;

    public Basket() {
        products = new ArrayList<>();
    }

    public void addProduct(Product product) {
        products.add(product);
    }

    public double getTotal() {
        double total = 0;
        for (Product product : products) {
            total += product.getPrice();
        }
        return total;
    }
}

class Order {
    public double calculateTotal(Basket basket) {
        return basket.getTotal() + 5.0; // Add 5.0 for shipping
    }
}

public class Main {
    public static void main(String[] args) {
        Basket basket = new Basket();
        basket.addProduct(new Product("Item 1", 10.0));
        basket.addProduct(new Product("Item 2", 20.0));

        Order order = new Order();
        double total = order.calculateTotal(basket);
        System.out.println("Total: " + total); // Output: Total: 35.0
    }
}

Output

Total: 35.0

Explanation
In the above java program, we’ll use association to create an Order object that uses a Basket object as a parameter for its calculateTotal method.
In this example, the Order class uses an instance of the Basket class as a parameter of the calculateTotal method. The Basket class can exist independently of the Order class, but the Order class needs a Basket object to calculate the total price of the order. The calculateTotal method of the Order class calls the getTotal method of the Basket class to get the total price of the products in the basket.

Aggregation in Java

Aggregation in Java is a concept that allows objects to be composed of other objects. It is a type of relationship between two classes, where one class has a reference to another class as one of its instance variables. In this way, the class that contains the reference can use the functionality of the other class.
Here is an example of aggregation in Java:

 class Address {
    private String street;
    private String city;
    private String state;
    private String zipCode;

    public Address(String street, String city, String state, String zipCode) {
        this.street = street;
        this.city = city;
        this.state = state;
        this.zipCode = zipCode;
    }

    public String toString() {
        return street + ", " + city + ", " + state + " " + zipCode;
    }
}

class Person {
    private String name;
    private int age;
    private Address address;

    public Person(String name, int age, Address address) {
        this.name = name;
        this.age = age;
        this.address = address;
    }

    public String toString() {
        return name + ", " + age + ", " + address.toString();
    }
}

public class Main {
    public static void main(String[] args) {
        Address address = new Address("123 Main St", "Anytown", "CA", "12345");
        Person person = new Person("Mohit", 30, address);
        System.out.println(person.toString());
    }
}

Output

Mohit, 30, 123 Main St, Anytown, CA 12345

Explanation
In this example, we have two classes: Address and Person. The person contains an instance variable of type Address. This is an example of aggregation because the Person class is composed of an Address object. The Address class has a constructor that takes in four parameters: street, city, state, and zip code. It also has a toString() method that returns a formatted string representation of the address. The Person class has a constructor that takes in three parameters: name, age, and address. It also has a toString() method that returns a formatted string representation of the person, including their name, age, and address. In the Main class, we create an Address object and a Person object, passing the Address object as an argument to the Person constructor. We then call the toString() method on the Person object and print the result to the console. This demonstrates how aggregation works in Java. The Person class has a reference to an Address object, which it can use to access the functionality of the Address class.

Composition in Java

Composition in Java is a "has-a" relationship between two classes, where one class (the composite) contains an instance of the other class (the component) as a field or property.

Code Implementation

 class Engine {
    private int horsepower;

    public Engine(int horsepower) {
        this.horsepower = horsepower;
    }

    public int getHorsepower() {
        return horsepower;
    }
}

class Car {
    private String make;
    private String model;
    private Engine engine;

    public Car(String make, String model, Engine engine) {
        this.make = make;
        this.model = model;
        this.engine = engine;
    }

    public void start() {
        System.out.println("Starting " + make + " " + model + " with " + engine.getHorsepower() + " horsepower engine.");
    }
}

public class Main {
    public static void main(String[] args) {
        Engine engine = new Engine(200);
        Car car = new Car("Toyota", "Camry", engine);
        car.start();
    }
}

Output

Starting Toyota Camry with 200 horsepower engine.

Explanation
In this example, the Car class has a composition relationship with the Engine class. The Car class has an instance variable called engine that holds a reference to an Engine object. The Car class also has a method called start(), which uses the Engine object to output a message that starts the car. The Main class creates an instance of an Engine with 200 horsepower and an instance of Car with a Toyota make and Camry model, passing the Engine object to the Car constructor.

When the start() method is called on the Car object, it outputs the message "Starting Toyota Camry with 200 horsepower engine."The composition relationship between the Car and Engine classes means that the Engine object is an integral part of the Car object. The lifetime of the Engine object is tightly coupled with the lifetime of the Car object, and the Engine object cannot exist independently of the Car object.

Difference between Aggregation and Composition in Java

Here we have the Difference between composition and Aggregation in java

Aggregation Composition
A relationship between two classes where one class is a container of another class, but the contained class can exist independently of the container class. A relationship between two classes where one class is composed of the other class, and the composed class cannot exist without the container class.
It is a weak Association It is a strong Association
The contained class can be created before or after the container class is created. The composed class must be created before the container class is created.
The container class does not have ownership over the contained class. The container class has ownership over the composed class.
Example:  A car has an engine, but the engine can exist without a car Example: A car has wheels, but the wheels cannot exist without the car

Conclusion
In conclusion, mastering the concepts of Association, Composition, and Aggregation is crucial for designing well-architected and scalable Java applications. Each of these relationships plays a distinct role in shaping the structure of a program, influencing how classes interact and collaborate. While Association establishes connections, Composition creates a strong relationship emphasizing ownership, and Aggregation provides flexibility with a more relaxed association.
Choosing the right type of relationship is essential for creating code that is not only efficient but also easy to understand and maintain. Java’s object-oriented features, coupled with a clear understanding of these concepts, empower developers to craft flexible and extensible systems that can adapt to changing requirements.

Frequently Asked Questions related to Association, Composition, and Aggregation in Java

Here are the FAQs related to Association, Composition, and Aggregation in Java:

Q1: What is the main difference between Association and Composition in Java?
A1:
Association represents a simple connection between classes, while Composition is a stronger relationship where one class owns another class. In Composition, the "part" class cannot exist independently of the "whole" class.

Q2: How does Aggregation differ from Composition in Java?
A2:
Aggregation is a more loosely coupled association compared to Composition. In Aggregation, the "part" class can exist independently of the "whole" class. It represents a relationship where objects are related, but their lifecycles are not necessarily tied together.

Q3: Can a class be associated with multiple classes in Java?
A3:
Yes, a class can be associated with multiple classes in Java. This is a common scenario in complex systems where different classes collaborate to achieve a particular functionality.

Q4: When should I use Composition over Aggregation in Java?
A4:
Use Composition when one class is a fundamental part of another class, and the two are tightly bound. Use Aggregation when objects are related, but they can exist independently, and the relationship is more relaxed.

Q5: Are there any built-in mechanisms in Java for handling Association, Composition, or Aggregation?
A5:
Java itself does not have built-in keywords or mechanisms specifically for Association, Composition, or Aggregation. These concepts are implemented using class relationships, and the choice between them depends on the design goals and requirements of the application.

Leave a Reply

Your email address will not be published. Required fields are marked *