Login

Username:

Password: 

Join us Now |  Forgot Password? | Forgot UserName?

Java

Learn step by step



Aggregation in Java

If a class have an entity reference, it is known as Aggregation. Aggregation represents HAS-A relationship.
Consider a situation, Employee object contains many informations such as id, name, emailId etc. It contains one more object named address, which contains its own informations such as city, state, country, zipcode etc. as given below.

class Student
{
String name;
Address ad;
}

Here you can say that Student has-a Address.

aggregation

Fig1.

Student class has an instance variable of type Address. Student code can use Address reference to invoke methods on the Address, and get Address behavior.

Aggregation allow you to design classes that follow good Object Oriented practices. It also provide code reusability.


class Author
{
String authorName;
int age;
String place;
Author(String name,int age,String place)
{
this.authorName=name;
this.age=age;
this.place=place;
}
public String getAuthorName()
{
return authorName;
}
public int getAge()
{
return age;
}
public String getPlace()
{
return place;
}
}

class Book
{
String name;
int price;
Author auth;
Book(String n,int p,Author at)
{
this.name=n;
this.price=p;
this.auth=at;
}
public void showDetail()
{
System.out.println("Book is"+name);
System.out.println("price "+price);
System.out.println("Author is "+auth.getAuthorName());
}
}

class Test
{
public static void main(String args[])
{
Author ath=new Author("Me",22,"India");
Book b=new Book("Java",550,ath);
b.showDetail();
}
}

Output

Book is Java.
price is 550.
Author is me.


In this example, we have created the reference of Operation class in the Circle class.

class Operation{
int square(int n){
return n*n;
}
}
class Circle{
Operation op;//aggregation
double pi=3.14;

double area(int radius){
op=new Operation();
int rsquare=op.square(radius);//code reusability (i.e. delegates the method call).
return pi*rsquare;
}

public static void main(String args[]){
Circle c=new Circle();
double result=c.area(5);
System.out.println(result);
}
}

Output

78.5

When use Aggregation?

  • Code reuse is also best achieved by aggregation when there is 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.



Related Videos