📅  最后修改于: 2020-09-24 00:42:17             🧑  作者: Mango
如果类具有实体引用,则称为聚合。聚集表示HAS-A关系。
考虑一种情况,Employee对象包含许多信息,例如id,名称,emailId等。它还包含一个名为address的对象,该对象包含自己的信息,例如城市,州,国家/地区,邮政编码等,如下所示。
class Employee{
int id;
String name;
Address address;//Address is a class
...
}
在这种情况下,雇员具有实体引用地址,因此关系为雇员HAS-A地址。
在此示例中,我们在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);
}
}
在此示例中,员工有一个地址对象,地址对象包含其自己的信息,例如城市,州,国家等。在这种情况下,关系是员工HAS-A地址。
public class Address {
String city,state,country;
public Address(String city, String state, String country) {
this.city = city;
this.state = state;
this.country = country;
}
}
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("gzb","UP","india");
Address address2=new Address("gno","UP","india");
Emp e=new Emp(111,"varun",address1);
Emp e2=new Emp(112,"arun",address2);
e.display();
e2.display();
}
}