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 vipul{
- int id;
- String name;
- Address address;//Address is a class
- ...
- }
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.
- aggregation is the best choice.
Example
- class one{
- int square(int n){
- return n*n;
- }
- }
- class two{
- Operation op;//aggregation
- double pi=3.14;
- double area(int radius){
- op=new one();
- int rsquare=op.square(radius);//code reusability (i.e. delegates the method call).
- return pi*rsquare;
- }
- public static void main(String args[]){
- two c=new two();
- double result=c.area(5);
- System.out.println(result);
- }
- }