What Is Association In Java?

We shall talk about Association in Java in this post. Through their shared objects, association builds a connection between two distinct classes. One-to-one, one-to-many, many-to-one, and many-to-many relationships are all possible.

Association Example

class CarClass{
   String carName;
   int carId;
   CarClass(String name, int id)
	this.carName = name;
	this.carId = id;
class Driver extends CarClass{
   String driverName;
   Driver(String name, String cname, int cid){
	super(cname, cid);
class TransportCompany{
   public static void main(String args[])
	Driver obj = new Driver("Andy", "Ford", 9988);
	System.out.println(obj.driverName+" is a driver of car Id: "+obj.carId);


Andy is a driver of car Id: 9988

In the aforementioned example, CarClass and Driver have a one-to-one connection (Association). Both classes stand for two distinct entities.

Association vs Aggregation vs Composition

Lets discuss difference between Association, Aggregation and Composition:

Despite the fact that all three phrases pertain to two classes, there are some significant distinctions in how they do so. An association is a connection between two distinct classes, and it may take any form, such as one to one, one to may, etc. It combines two very different entities.

Aggregation is a specific kind of connection that has a one-way, unidirectional relationship between classes (or entities), for as the classes Wallet and Money. It’s a one-way interaction since money has Wallet but doesn’t necessarily need to have Wallet. In this connection, even if one entry disappears, the other one may still exist. In our example, the absence of the Wallet class does not exclude the existence of the Money class.

Two things (or, you might say, classes) that are heavily reliant on one another are said to be in a composition, which is a constrained kind of aggregation. Heart and Human, for instance. To survive, a human body must have a heart, and vice versa. In other terms, a composition occurs when classes (entities) are interdependent and have a fixed lifespan (i.e., if one dies, the others do too). If Human class is absent, Heart class is meaningless.


Related Articles

Leave a Reply

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

Back to top button