Java 聚合



Java 聚合

如果类具有实体引用,则称为聚合。聚集表示HAS-A关系。考虑一种情况,Employee对象包含许多信息,例如id,name,emailId等。它还包含一个名为address的对象,该对象包含自己的信息,例如城市,州,国家/地区,邮政编码等,如下所示。
class Employee{ 

int id;
String name;
Address address;//Address is a class
...
}

在这种情况下,雇员具有实体引用地址,因此关系为雇员HAS-A地址。

为什么要使用聚合?

用于代码可重用性。

聚合的简单示例

Java 聚合_https://bianchenghao6.com_【Java 基础教程】_第1张

在此示例中,我们在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关系时,通过聚合也可以最好地实现代码重用。
只有在关系-a在所涉及对象的整个生命周期中都保持不变时,才应使用继承。否则,聚合是最佳选择。

Address.java
 public class Address { 
String city,state,country;
 
public Address(String city, String state, String country) {
    this.city = city;
    this.state = state;
    this.country = country;
}
 
}

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.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();
    }
}

输出:
 111 varun
gzb UP india
112 arun
gno UP india