Agregacija (HAS-A) u Javi
Ako klasa ima referencu na neki entitet, to je poznato kao agregacija.
Agregacija predstavlja HAS-A relaciju.
Razmotrimo sledeću situaciju: objekat Employee sadrži mnoge informacije kao što su id, name, email itd. On sadrži još jedan objekt koji se zove address, koji sadrži svoje sopstvene informacije kao što su grad, republika ili kanton, država, zipcode itd. kao što je prikazano ovde:
U ovakvom slučaju, Employee ima referencu na entitet address, tako da je relacija Employee HAS-A address. Zašto se koristi agregacija? • zbog ponovne upotrebljivosti (reusability) koda. Jednostavan primer agregacije
U ovom primeru, kreiraćemo referencu klase Operation u klasi Circle.
Kada se koristi agregacija?
1
2
3
4
5
6 |
class Employee{ int id; String name; Address address; //Address je klasa ... } |

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26 |
class Operation{ int square( int n){ return n*n; } } class Circle{ Operation op; //agregacija double pi= 3.14 ; double area( int radius){ op= new Operation(); int rsquare=op.square(radius); //ponovna upotrebljivost koda return pi*rsquare; } public static void main(String args[]){ Circle c= new Circle(); double result=c.area( 5 ); System.out.println(result); } } Ispis na ekranu: 78.5 |
- Ponovna upotreba koda se najbolje postiže pomoću agregacije onda kada nema relacije is-a.
- Nasleđivanje se treba koristiti samo ako se relacija is-a održava tokom svog vremena života uključenog objekta; inače, agregacija je najbolji izbor.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48 |
// file: Address.java package Emp; public class Address { String city,state,country; public Address(String city, String state, String country) { this .city = city; this .state = state; this .country = country; } } ///////////////////////////////////////////////////////////////// // file: Emp.java package Emp; public class Emp { int id; String name; Address address; public Emp( int id, String name, Address address) { this .id = id; this .name = name; this .address = address; } void display() { System.out.println(id + " " + name); System.out.println(address.city + " " + address.state + " " + address.country); } public static void main(String[] args) { Address address1 = new Address( "BL" , "RS" , "BiH" ); Address address2 = new Address( "BN" , "RS" , "BiH" ); Emp e = new Emp( 111 , "Petar" , address1); Emp e2 = new Emp( 112 , "Marko" , address2); e.display(); e2.display(); } } Ispis na ekranu: 111 Petar BL RS BiH 112 Marko BN RS BiH |