Java 聚合,聚合是一种特殊的关联形式。它是关联这两个类之间的关系,然而它是方向关联,这意味着它严格地是单向关联。 它代表 HAS-A 的关系。
Java 中的聚合示例
例如,考虑两个类Student
类和Address
类。每个学生都有一个地址,所以学生和地址之间的关系是一个 Has-A 关系。但如果你认为反之亦然那么它就没有任何意义,因为Address
不一定需要Student
。让我们在 java 程序中编写这个例子。
Student Has-A Address
class Address
{
int streetNum;
String city;
String state;
String country;
Address(int street, String c, String st, String coun)
{
this.streetNum=street;
this.city =c;
this.state = st;
this.country = coun;
}
}
class StudentClass
{
int rollNum;
String studentName;
//Creating HAS-A relationship with Address class
Address studentAddr;
StudentClass(int roll, String name, Address addr){
this.rollNum=roll;
this.studentName=name;
this.studentAddr = addr;
}
public static void main(String args[]){
Address ad = new Address(55, "Agra", "UP", "India");
StudentClass obj = new StudentClass(123, "Chaitanya", ad);
System.out.println(obj.rollNum);
System.out.println(obj.studentName);
System.out.println(obj.studentAddr.streetNum);
System.out.println(obj.studentAddr.city);
System.out.println(obj.studentAddr.state);
System.out.println(obj.studentAddr.country);
}
}
输出:
123
Chaitanya
55
Agra
UP
India
上面的例子显示了Student
和Address
类之间的 聚合 。你可以看到在Student
类中我已经声明了一个Address
类型的属性来获取学生地址。它是 Java 中聚合的典型示例。
为什么我们需要聚合
维护代码重用性。要理解这一点,请再次使用相同的示例。假设还有另外两个类College
和Staff
以及上面两个类Student
和Address
。为了保持学生的地址,学院地址和工作人员的地址,我们不需要一次又一次地使用相同的代码。我们只需要在定义每个类时使用Address
类的引用,如:
Student Has-A Address (Has-a relationship between student and address)
College Has-A Address (Has-a relationship between college and address)
Staff Has-A Address (Has-a relationship between staff and address)
因此,我们可以通过使用聚合关系来提高代码的可重用性。
所以,如果我必须在一个程序中写这个,我会这样做:
class Address
{
int streetNum;
String city;
String state;
String country;
Address(int street, String c, String st, String coun)
{
this.streetNum=street;
this.city =c;
this.state = st;
this.country = coun;
}
}
class StudentClass
{
int rollNum;
String studentName;
//Creating HAS-A relationship with Address class
Address studentAddr;
StudentClass(int roll, String name, Address addr){
this.rollNum=roll;
this.studentName=name;
this.studentAddr = addr;
}
...
}
class College
{
String collegeName;
//Creating HAS-A relationship with Address class
Address collegeAddr;
College(String name, Address addr){
this.collegeName = name;
this.collegeAddr = addr;
}
...
}
class Staff
{
String employeeName;
//Creating HAS-A relationship with Address class
Address employeeAddr;
Staff(String name, Address addr){
this.employeeName = name;
this.employeeAddr = addr;
}
...
}
正如您所看到的,我们没有在三个类中的任何一个中编写Address
代码,我们只是使用Address
类创建了 HAS-A 关系以使用Address
代码。上面代码中的点点(…)部分可以用public static void main
方法替换,其中的代码与我们在第一个例子中看到的类似。