易百教程

62、什么是聚合?

聚合可以定义为两个类之间的关系,其中聚合类包含对其拥有的类的引用。 聚合最好描述为具有关系。 例如,具有诸如年龄、姓名和薪水等各种字段的聚合类 Employee 还包含具有诸如 Address-Line 1、City、State 和 pin-code 等各种字段的 Address 类的对象。换句话说, Employee(类)有一个 Address 类的对象。 考虑以下示例:
文件:Address.java

package com.yiibai.demo;

public class Address {

    String city, state, country;

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

}

文件:Employee.java

package com.yiibai.demo;

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("Sanya", "hainan", "China");
        Address address2 = new Address("Haikou", "hainan", "China");

        Emp e = new Emp(111, "Name1", address1);
        Emp e2 = new Emp(112, "Yiibai", address2);

        e.display();
        e2.display();
    }
}

运行结果:

111 Name1
Sanya hainan China
112 Yiibai
Haikou hainan China