Last Updated on March 28, 2023 by Prepbytes
Association, composition, and aggregation are three different concepts that are commonly used in object-oriented programming languages such as Java. These concepts describe the relationship between different classes and objects in a Java program. An association is a relationship that exists between two distinct classes and is established through their Objects and this relationship can be One-to-one, one-to-many, many-to-one, and many-to-many Composition and aggregation are the two forms of association. Here we discussed Association, Composition, and Aggregation in Java
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 |
Summary
Association, composition, and aggregation are three fundamental relationships in object-oriented programming in Java.
- Association in java represents a "uses-a" relationship between two or more classes. In Java, the multiplicity between objects is defined by the Association. It shows how objects communicate with each other and how they use the functionality and services provided by that communicated object. Association manages one-to-one, one-to-many, many-to-one and many-to-many relationships.
- Composition in java is a "part-of" relationship between a composite object and its component objects. 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 composition. Composition occurs when one object contains another object and the contained object cannot exist without the existence of that object. In more specific words composition is a way of describing reference between two or more classes using an instance variable and an instance should be created before it is used.
- Aggregation in java is also a "part-of" relationship between a composite object and its component objects. However, in aggregation, the component objects can exist independently of the composite object. The composite object has a reference to the component objects, but the component objects can exist without the composite object.
Understanding these relationships is essential in designing object-oriented software in Java. By choosing the appropriate relationship, developers can create robust and maintainable code. In summary, the association is a "uses-a" relationship, the composition is a "part-of" relationship with a tight coupling between objects, and aggregation is a "part-of" relationship with a loose coupling between objects.
Frequently Asked Questions
Here are the FAQs
Q1. What is the difference between association and composition in Java?
Ans. Association is a "uses-a" relationship between two classes, while the composition is a "part-of" relationship between a composite object and its component objects. In association, the objects can exist independently of each other, whereas, in composition, the lifetime of the component objects is tightly coupled with the lifetime of the composite object.
Q2. What is the difference between composition and aggregation in Java?
Ans. Composition and aggregation are both "part-of" relationships, but in composition, the component objects are integral parts of the composite object and cannot exist independently of it. In contrast, in aggregation, the component objects can exist independently of the composite object.
Q3. How are these relationships implemented in Java?
Ans. These relationships are implemented in Java using class variables or instance variables that reference other classes. In composition and aggregation, the component objects are usually created and initialized in the constructor of the composite object.
Q4. Can an object be part of multiple composite objects?
Ans. No, an object can only be part of one composite object in a composition relationship. However, in an aggregation relationship, an object can be part of multiple composite objects.
Q5. When should I use association, composition, or aggregation in Java?
Ans. Association should be used when one class uses the services of another class, the composition should be used when the component objects are integral parts of the composite object, and aggregation should be used when the component objects can exist independently of the composite object.