什么时候使用聚合呢?

Java-教程王 Java教程 发布时间:2021-04-13 14:40:55 阅读数:3832 1

何时使用聚合?

  • 当类与类之间没有继承关系时,此时为了更好的代码重用,我们可以使用聚合来达到代码的重用  

Java聚合的示例

       Employee中放入Address对象
       address对象包含其自己的信息,
           例:城市,州,国家等

        下文讲述Employee对象中聚合address对象

Address.java

public class Address {
    String city, province;

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

}


Employee.java

public class Employee{
    int id;
    String name;
    Address address;

    public Employee(int id, String name, Address address) {
        this.id = id;
        this.name = name;
        this.address = address;
    }

    void printInfo() {
        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("三亚", "海南");

        Employee e = new Employee(888, "java265.com", address1);
        Employee e2 = new Employee(999, "javaTest", address2);

        e.printInfo();
        e2.printInfo();

    }
}
 
 
 
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

本文链接: https://www.Java265.com/JavaCourse/240.html

最近发表

热门文章

好文推荐

Java265.com

https://www.java265.com

站长统计|粤ICP备14097017号-3

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者