I would like to know the proper way to implement UML association class in Java programming code. I have Student and Course classes. Student can attend one or more Courses, Courses can be attended by one or more Student (many-to-many relationship). If I don't have any attribute in association class (despite course and student ids), would it be okey to implement it this way: public class Course{ private List<Student> students ...}
public class Student{ private List<Course> course}
. Please explain me both situations, because I don't get it if I should have model public CourseEnrollment { private Student; private Course; private LocalDate enrollementDate}
and lists of CourseEnrollments in Student and Course classes.
What I tried is explained above with CourseEnrollment class and my doubts.
One easy way to implement an association class is to use a Collection<CourseEnrollment>
e.g. an ArrayList<CourseEnrollment>
, in both Course
and Student
, and make sure that CourseEnrollment has a property back to the respective Course
and Student
.
The navigation would then be indirect: Student -> List of enrolments -> corresponding courses, or Course -> List of enrolments -> corresponding students. The challenge in your code will be to maintain consistency, e.g. if your remove a student from a course, you'll need not only to delete the enrollment from the course's collection, but also from the student's collection.
Another alternative is to use an independent repository of CourseEnrollments
, that keeps a list of all the enrolments and provides efficient access for a student and a course, through two HashMap
. The advantage is that there's only one place to manage the enrollment, and students or courses can get the relevant and up-to-date links from there. Again, navigation is indirect, this time by querying the repository. The challenge here is to manage decoupling, since every Student
or Course
would need to know about the repository.
You may have noticed, that in both cases, the trick is to implement the association class as a class, and to decompose the direct association between Student
and Course
into an indirect association via the association class.
P.S: In the UML semantics, the association class is at the same time a class and an association. But it can have only one name. Chose either chooses
or CourseEnrollment
, but you should not use different names.