I understand the differences in theory, but what is the difference in the code implementation? Can somebody provide some examples?
Asked
Active
Viewed 2,402 times
1
-
1Thanks for the answers. http://stackoverflow.com/questions/4298177/association-vs-aggregation (third answer) also helped. I have a final uncertainty I hope someone can address. Am I correct in believing instances of the associated class in this diagram http://img152.imageshack.us/img152/4981/21083939.png would have to be owned by a class not shown in the diagram (otherwise an aggregate relationship would have to exist between whole and associated class?)? – amax Dec 06 '10 at 14:50
2 Answers
3
Purpose we have students and universities
class University {
private final Set<Student> students = new HashSet<Student>();
void addStudent(Student s){students.add(s);}
}
class Student {
private final String name;
public Student(String name) {
this.name = name;
}
}
We create this stuff in some way
University university = new University();
Student bob = new Student("Bob");
university.addStudent(bob);
And know we need to know does Bob studies in university. So we create some new method for university
boolean contains(Student student){
for(Student s : students){
if(s.equals(student)) return true;
}
return false;
}
and, than do smt like university.contains(bob)
.
But what will be if we havent link to uniwersity. We need to ask it Bob. But Bob doesn't know. So we go from composition to bi-derection and create smt like
class University {
private final Set<Student> students = new HashSet<Student>();
void addStudent(Student s){
students.add(s);
s.setUniversity(this);
}
boolean contains(Student student){
for(Student s : students){
if(s.equals(student)) return true;
}
return false;
}
}
class Student {
private final String name;
private University university;
public Student(String name) {
this.name = name;
}
void setUniversity(University u){
university = u;
}
boolean doYouStudyInUniversity(){
return university != null;
}
}
//ask
bob.doYouStudyInUniversity();

Stan Kurilin
- 15,614
- 21
- 81
- 132
-
Should we enforce the setUniversity and addStudent in the constructor to make sure that they will always be called when a new Student is created? – Kenston Choi Jun 24 '12 at 03:49
-
@Kenston Choi, it depends from your coding style/paradigm you are using. Anyway it quite challenging to construct immutable bidirectional structures in Java (you can imitate it using proxies). – Stan Kurilin Jul 11 '12 at 16:10
0
Composition is, in effect, uni-directional association - except that semantically, we interpret it as meaning "that thing is part of this thing" rather than simply "this thing holds a reference to that thing".

Karl Knechtel
- 62,466
- 11
- 102
- 153