The use of a class set not only represents a one-to-one relationship, but also represents a many-to-many relationship. For example, if a student can select multiple courses and multiple students can participate in one course, this is a typical multi-to-many relationship.
To complete this program, we should first define two categories: Student Information Student and Course information Course. There is a set in a student class to save all the courses. There must also be a set in the course class to save all the students.
Example: Define Student Class
- PackageOrg.lxh.demo13.exe cdemo02;
- ImportJava. util. ArrayList;
- ImportJava. util. List;
- Public ClassStudent {// Define the Student Category
- PrivateString name;// Define the name attribute
- Private IntAge;// Define the age attribute
- PrivateList <Course> allCourses;// Define a set to save all courses
- PublicStudent (){// No parameter structure
- This. AllCourses =NewArrayList <Course> ();// Instantiate the List set
- }
- PublicStudent (String name,IntAge ){// Set the attribute content by constructing
- This();// Call construction without Parameters
- This. SetName (name );// Set the name attribute content
- This. SetAge (age );// Set the age attribute content
- }
- PublicString getName (){// Obtain the name attribute
- ReturnName;
- }
- Public VoidSetName (String name ){// Set the name attribute
- This. Name = name;
- }
- Public IntGetAge (){// Obtain the age attribute
- ReturnAge;
- }
- Public VoidSetAge (IntAge ){// Set the age attribute
- This. Age = age;
- }
- PublicList <Course> getAllCourses (){// Obtain all courses
- ReturnAllCourses;
- }
- PublicString toString (){// Override the toString () method
- Return