聚合
如果一个类有一个类的实体引用(类中的类),则它称为聚合。 聚合表示has-a关系。
考虑有一种情况,employee
对象包含许多信息,例如:id
,name
,emailid
等。它包含另一个类对象:address
,其包含它自己的信息,例如:城市,州,国家,邮政编码等,如下所示。
class employee{
int id;
string name;
address address;//address is a class
...
}
在这种情况下,employee
有一个实体引用地址(address
),因此关系是:employee has-a address
。
在这个例子中,在circle
类中创建了operation
类的引用。
class operation {
int square(int n) {
return n * n;
}
}
class circle {
operation op;// aggregation
double pi = 3.14;
double area(int radius) {
op = new operation();
int rsquare = op.square(radius);// 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);
}
}
执行上面代码,得到以下结果 -
78.5
is-a
关系时,通过聚合也能最好地实现代码重用。is-a
时,才应使用继承; 否则,聚合是最好的选择。在此示例中,employee
中拥有address
对象,address
对象包含其自己的信息,例如城市,州,国家等。在这种情况下,关系是员工(employee
)has-a
地址(address
)。
address.java
public class address {
string city, province;
public address(string city, string province) {
this.city = city;
this.province = province;
}
}
emp.java
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.province);
}
public static void main(string[] args) {
address address1 = new address("广州", "广东");
address address2 = new address("海口", "海南");
emp e = new emp(111, "wang", address1);
emp e2 = new emp(112, "zhang", address2);
e.display();
e2.display();
}
}
执行上面代码,得到以下结果 -
111 wang
广州 广东
112 zhang
海口 海南