I have a problem about implementing a 1 to 1 association in java. For example, conside the following class diagram:
I implement it like this:
public class Student{
private AttendanceRole attendance;
public Student(AttendanceRole attendance){
this.attendance=attendance;
addTwoWayLink(this); //creates the two-way link between objects
}
public void setAttendanceRole(AttendanceRole a){ //if a students changes from
attendance = a; //part time to full time
}
}
public class AttendanceRole{
private Student student;
void addTwoWayLink(Student student){
this.student=student;
}
}
Here is the problem:
1) Assume i created a student object and i want to change the attendance role of a student. In this case, i call setAttendanceRole method. But i have to give it an AttendanceRole object as a parameter. Since this is a 1 to 1 relationship, the parameter i give also has a student associated with it. So, this is a problem. Also i can't create an AttendanceRole object without a link to a student since this is a 1 to 1 association. The same situation occurse when i first try to create a student object and call its constructor. I can give null as parameter value, but in this case don't i harm the 1 to 1 relationship constraint? What can i do about it?
2)Also, i design this class so that we can create a student object and set its AttendanceRole. I mean we cannot create an AttendanceRole object and set its student. Is this a bad idea? Or is it up to designer which object will be created first.
Thank you