Java Drmbs Unit 3 Aggregation
Java Drmbs Unit 3 Aggregation
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.
1. class Employee{
2. int id;
3. String name;
4. Address address;//Address is a class
5. ...
6. }
In such case, Employee has an entity reference address, so relationship is Employee HAS-A
address.
In this example, we have created the reference of Operation class in the Circle class.
1. class Operation{
2. int square(int n){
3. return n*n;
4. }
5. }
6.
7. class Circle{
8. Operation op;//aggregation
9. double pi=3.14;
10.
11. double area(int radius){
12. op=new Operation();
13. int rsquare=op.square(radius);//code reusability (i.e. delegates the method call).
14. return pi*rsquare;
15. }
16.
17.
18.
19. public static void main(String args[]){
20. Circle c=new Circle();
21. double result=c.area(5);
22. System.out.println(result);
23. }
24. }
Output:78.5
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.
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
Output:111 varun
gzb UP india
112 arun
gno UP india