Thursday, 11 December 2014

What is Aggregation in java ?

Aggregation :

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 eid, name, emailId etc. It contains one more object named address, which contains its own informations such
as city, state, country etc. as given below.

class Employee{
int eid;
String name;
Address address;   //Address is a class
.....
}

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

Understanding meaningful example of Aggregation:

In this example, Employee has an object of Address, address object contains its own informations such as city, state, country etc. In such case relationship  is Employee HAS-A address.

Address.java:

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

Employee.java

public class Employee {
int id;
String name;
Address address;
public Employee(int id, String name,Address address) {
this.id = id;
this.name = name;
this.address=address;
}
void show(){
System.out.println(id+" "+name);
System.out.println(address.city+" "+address.state+" "+address.country);
}
public static void main(String []args) {
Address address1=new Address("GKP","UP","india");
Address address2=new Address("Agra","UP","india");
Employee e1=new Employee(123,"vishwa",address1);//here code reusability
Employee e2=new Employee(456,"dolly",address2);//here code reusability
e1.show();
e2.show();
  }
}

Output: 123 vishwa
                GKP UP india
                456 dolly
               Agra UP india

Why use Aggregation ?

>For Code Reusability.

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.

No comments:

Post a Comment