Java Design Pattern
Introduction to Java 10
Introduction to Java 11
Introduction to Java 12

Java Aggregation

When the reference of a class act as a member in another class is known as Aggregation.

Aggregation represents HAS-A relationship. Consider a situation, Employee object contains many information such as id, name etc. It contains one more object named address, which contains its own information such as city, state, country etc.

It represent the concept of inheritance without no IS-A relationship. Inheritance should be used only if the relationship IS-A is maintained throughout the lifetime of the objects involved; otherwise, aggregation is the best choice.

Let's see an example for better understanding this concept.


Address.java

package java8s;

publicclass Address 
{
	String city, state, country;
	Address(String city, String state, String country)
	{
		this.city=city;
		this.state=state;
		this.country=country;
	}
}

AgreegationExample.java

package java8s;

class Employee
{
	int id;
	String name;
	Address ad;
	Employee(int id, String name, Address ad)
	{
		this.id=id;
		this.name=name;
		this.ad=ad;
	}

	void show()
	{
		System.out.println(id+" "+name);
		System.out.println(ad.city+" "+ad.state+" "+ad.country);
	}
}
publicclass AgreegationExample 
{

	publicstaticvoid main(String[] args) {
	   
		Address ob1=new Address("BBSr","Odisha","india");
		Employee e=new Employee(101,"Trilochan",ob1);
		e.show();

	}

}

Output

aggregation

Note:
When we need to use property and behaviour of a class without modifying it inside our class then we use Aggregation as better, Whereas when we need to use and modify property and behaviour of a class inside our class, then we use Inheritance as better.

About the Author



Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.


We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc






 PreviousNext