Code Aggregation *for code reusability

What is Code Aggregation

code aggregation
Code aggregation as reusability

If there is an entity reference in a class, then you what you have is a code aggregation. Aggregation usually represents HAS-A relationship.
Consider the following situation situation.

A Worker object contains many informations such as id, name, phone number etc. It contains one more object named address, which contains its own informations such as city, state, country etc. see it as given below.


class Worker{
int id;
String name;
Address address;//Address is a class

}

In such case, the Worker has an entity reference address, so the relationship is : Employee HAS-A address.

Furthermore if you wonder a question, why do we bother doing aggregation. It’s because aggregation it used for a code reusability  led to efficiency.
As a result here, take a loot at this Simple Example of Aggregation :

Circle Operation
double pi
area(int radius) -> square(int n)

In addition this example tells the relationship is : area(int radius) HAS-A operation which is square(int n)

Now finally I’m going to give you a simple exmpl of Aggregation :

class OperationExmpl{
int square(int n){
return n*n;
}
}

class Circle{
Operation op;// this is the aggregation
double pi=3.14;
double area(int radius){ 


op=new OperationExmpl(); 
int rsquare=op.square(radius);// and this is called the 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);
}
}
And this will output :

78.5

And maybe you still wonder, when do we need to use aggregation ?

  • Code reuse / reusability is also best achieved by aggregation when there is no is-a relationship. etc

Leave a Reply

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