什么时候使用聚合呢?
何时使用聚合?
- 当类与类之间没有继承关系时,此时为了更好的代码重用,我们可以使用聚合来达到代码的重用
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("三亚", "海南");
Employeee = new
Employee(888, "java265.com", address1);
Employeee2 = new
Employee(999, "javaTest", address2); e.
printInfo(); e2.printInfo(); } }
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。