Java聚合
聚合
如果一个类有一个类的实体引用(类中的类),则它称为聚合。 聚合表示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。
聚合示例:
地址类:
public class Address {
String city, province;
public Address(String city, String province) {
this.city = city;
this.province = province;
}
}
雇员类:
public class Employ {
int id;
String name;
Address address;
public Employ(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("乌鲁木齐", "新疆");
Employ e = new Employ(0820, "Wong", address1);
Employ e2 = new Employ(0528, "Lei", address2);
e.display();
e2.display();
}
}
输出结果
0820 Wong
深圳 广东
0529 Lei
乌鲁木齐 新疆