【发布时间】:2018-10-11 07:21:48
【问题描述】:
我正在通过下面的链接来找出组合和聚合之间的区别。
https://www.geeksforgeeks.org/association-composition-aggregation-java/
我能够理解,组合意味着孩子不能独立于父母而存在的关系,而聚合意味着孩子可以独立于父母而存在的关系。但无法理解我如何以编程方式区分它。下面是链接中给出的聚合和组合的示例。在这两种情况下,除了 Student 和 Department 类有一个额外的变量“name”之外,类在结构上是相同的。在组合中,“子不能独立于父”而存在,但是在这里我可以创建一个单独的 Book 对象并在不添加到 Library 的情况下使用它。
聚合
// student class
class Student
{
String name;
int id ;
String dept;
Student(String name, int id, String dept)
{
this.name = name;
this.id = id;
this.dept = dept;
}
}
/* Department class contains list of student
Objects. It is associated with student
class through its Object(s). */
class Department
{
String name;
private List<Student> students;
Department(String name, List<Student> students)
{
this.name = name;
this.students = students;
}
public List<Student> getStudents()
{
return students;
}
}
作曲
class Book
{
public String title;
public String author;
Book(String title, String author)
{
this.title = title;
this.author = author;
}
}
// Libary class contains
// list of books.
class Library
{
// reference to refer to list of books.
private final List<Book> books;
Library (List<Book> books)
{
this.books = books;
}
public List<Book> getTotalBooksInLibrary()
{
return books;
}
}
【问题讨论】:
-
您无法以编程方式区分组合与聚合。差异是相当哲学的。
标签: java oop aggregation composition