JavaScript Required

We're sorry, but we doesn't work properly without JavaScript enabled.

Looking for an Expert Development Team? Take two weeks Trial! Try Now

What is Association, Aggregation, Composition and Inheritance in Java with Example?

Introduction:

In Java, as you know everything revolves around “Classes and Object” only. So, you must know about the relationships between classes and objects to model or design any software Application. There are various relationship types exist in java called Association, Aggregation and composition. So, I am going to explain here about the Object-Oriented Programming concepts of Association, Aggregation and Composition and Inheritance.

The most exciting feature of object-oriented programming that mimics real-world objects. In other words, it (our code) tries to replicate real-world objects. When we talk about real-world objects, then the most complicated thing in real-world objects is relationships.

Association:

When we talk about the association in java, then this is nothing but a structural relationship, in object-oriented modeling, that specifies how objects are related to one another. This structural relationship can be shown in two forms:

Association represents the unidirectional or bidirectional relationship between two classes. If the Customer places an order, then this is a unidirectional association.

Bidirectional Association example: Person and Dog classes that setup a bidirectional association between a Person object and a Dog object. A Person object behaves like an owner for a Dog object and the Dog object behaves like a pet for the Person object. An association may exist between objects of different types or between the objects of the same type means of the same class. An association in UML is drawn as a solid line connecting the object of different classes or two objects of the same class.

If we want to show navigability, then we can use arrow (-->) at one end or both ends for bi-directional navigability. Here, if you see the below diagram then we have navigation from class A to class B. So class A somehow related to class B. So, we can say that class B is navigable from class A.

Association Aggregation Composition

There are many types of associations in Java-like one to one, one to many, many to many and many to one.

Aggregation

In Aggregation, the based object is standalone and can exist even if the object of the control class is dead. Let’s take an example: suppose we have a class Car and car has a dependent object as a Wheel. Now when we destroy the car, the Wheel object is still alive because the wheel can be fit into different cars. So, here the association between Car and Wheel is the aggregation.

First of all, to exist an aggregation relationship, there would be some association. In a plain association, classes are considered at the same level with one class having no more important than the other. Sometimes we do need to define a “whole/part” relationship where one class considered as a “whole” that consists of smaller classes that is considered as a “part”. This kind of relationship is called aggregation. It is also known as “Has-A” relationship as object of the whole has the object of the parts.

An aggregation in UML is drawn as an open diamond as below:

Association Aggregation Composition

Multiplicity here is: 1 means Exactly one instance and * means zero or more instance

See the above diagram. Employee is related to a company. Java Development Company can have one or many employees.

You can see the open diamond symbol. So, whenever you see open diamond symbol, that means it represents the aggregation in UML.

Aggregation and composition are both powerful forms of association. They both describe relationships between a whole and its parts. So, instead of “Has-A” relationship as a simple association, we deal with relationship that says is “part of” or reading relationship in other direction is “made of”.

Examples of this kind of relationship is Band made up of Musician or in other words Musician is a part of Band. Another example is Catalog made up of Product or we can say that Product is part of a catalog.

Association Aggregation Composition

1.*represents here At least one instance

Composition

As we have seen aggregation relationship makes a distinction between “whole” and “part”, but it does not force ownership. Also, the aggregation does not link the “whole” and “part” object in such a way that if the whole is destroyed then parts are also destroyed.

There is a variation of aggregation called “composition”. This has strong ownership, thus the scope of the whole and part are related. In composition, if there are two classes, class A(considered as a whole) and class B(considered as part) , then the destruction of class object will mean that class B object also does not exist. This also means that class B object may be a part of class A object only. So, this is a tight association. Composition in UML is drawn as a “filled diamond” at the whole end.

Association Aggregation Composition

So, here in the above diagram, we have a Department class and school class. There is a relationship exists from department to school.

The composition is an even stronger relationship than aggregation. To test for whether you are dealing with composition, you should use the “no-sharing rule”. This rule states that in a composition relationship, the part can belong to only one hole. So, in our example above does musician belong to only one band? This is not true. A musician can belong to a number of different bands. Same with the product-catalog relationship. Any particular product could appear in a number of different catalogs.

Now consider a relationship between a building and room as below. Can a room belong to more than one building? It can never be. So, this relationship is better described by composition than by aggregation.

Association Aggregation Composition

So, a composition relationship states that in this relationship the part can belong to only one whole and no sharing. Related to that if the whole is destroyed, then the part that makes it up is also destroyed. So, in our example, if we destroy a building, then the rooms also will get destroyed. On the other hand, with aggregation, this is not necessarily true. In our previous aggregation example of Band and Musician, suppose if a brand breaks up then the Musician that is part of this will not get destroyed and he/she can perform for other bands as well.

So, the main points about Composition in java that it supports has-A relationship and it can be implemented using instance variable in java. Composition supports code reusability. For example, if you consider the car class then the car has an engine. So, we can write like:

Public class Car { Private Engine engine; }

So, here we have implemented has-A relationship between Car and Engine using an instance variable. We can re-use the Engine class in other Car classes also thereby entertaining the code re-usability. Composition hides visibility to the client classes. Here, we can implement the Car in such a way that Engine class is not visible to client class. This is our choice of implementation.

Let’s see how we can achieve this:

public class Car { private Engine engine; public Car(String engineName, String engineType, String enginePower) { this.engine = new Engine(); engine.setEngineName(engineName); engine.setEngineTypee(engineType); engine.setEnginePower(enginePower); } public String getEngineName() { return engine.getEngineName(); } public static void main(String[] args) { Car c = new Car(“Turbo”, “Super”, “32 BHP”); c.getEngineName(); } }

Note: Here I have not provided a getter/setter method for Engine object. Because I want to hide the implementation from the outer world.

So, in my constructor, I am passing engine type, name and power and creating the engine object here. Then I have created the getter methods to retrieve the engine type, name, and power.

Aggregation vs composition Summary

Inheritance

Inheritance is basically Is-A relationship. We can achieve inheritance with the help of extends keyword. I believe you are already aware of the inheritance basics and the types of inheritance. I am discussing here the advantages of inheritance and how it is different from the Composition.

Main advantage of inheritance is code reusability. Suppose if Class B extends Class A, then all the properties of class A come into class B and we can access all the properties of Class A in Class B expect the private members. Also, we can call methods of A class using B class object.

Through inheritance, we can reduce redundancy.

Suppose we have a Class Car and Class Bus. Both of them are having startEngine() and stopEngine() method. Car class has openSunroof() and closeSunroof() method. Bus class have openGate() and closeGate() method.

Class Car { startEngine() {} stopEngine() {} openSunroof() {} closeSunroof() {} } Class Bus { startEngine() {} stopEngine() {} openGate() {} closeGate() {} }

So, here both Car and Bus class have same method startEngine() and stopEngine(). So, we have duplicate methods here and this is really a complex thing to maintain these duplicate methods in multiple classes.

So, for solving this problem, we can use inheritance. We can create a Vehicle class with two methods startEngine() and stopEngine(). Then we have to create two subclasses Car and Bus and these two classes will implement the Vehicle class to use the startEngine() and stopEngine() methods.

Class Vehicle { startEngine() {} stopEngine() {} } Class Car extends Vehicle { openSunroof() {} closeSunroof() {} } Class Bus extends Vehicle { openGate() {} closeGate() {} }

So, Inheritance entertains tight-coupling between the classes which is a disadvantage. Here Car class and Bus class is tightly coupled to Vehicle class. Car is a type of vehicle and same for bus also. So here Car is a vehicle. So, all the properties of a vehicle will get inherited to Car and Bus.

Deep dive: Composition vs Inheritance

Problems with inheritance:

So, in the above diagram, I have given an example of both Inheritance and Composition. In this example Coupling between Person and Animal is equal. Whether to use inheritance or composition?

If Animal is changed and Person may have to be changed or at least needs to be re-complied or re-deployed. With Composition, we get an extra benefit that we can not get with Inheritance. We can replace the Animal class on the right side with an interface.

SUMMARY

Inheritance:

Composition:

Conclusion:

Here, I have explained in details of the types of object relationships various examples illustrating Association, Aggregation and Composition and Inheritance in Java. Also, I have briefed about the scenarios where you have to take a design decision whether to go for composition or inheritance. I believe this article gave you enough information about modeling your application design in choosing aggregation or composition or inheritance concepts.

NSS Note

Some of our clients

team