Use a JAVA class to represent the "many-to-many" Relationship

Source: Internet
Author: User

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

 
 
  1. PackageOrg.lxh.demo13.exe cdemo02;
  2. ImportJava. util. ArrayList;
  3. ImportJava. util. List;
  4. Public ClassStudent {// Define the Student Category
  5. PrivateString name;// Define the name attribute
  6. Private IntAge;// Define the age attribute
  7. PrivateList <Course> allCourses;// Define a set to save all courses
  8. PublicStudent (){// No parameter structure
  9. This. AllCourses =NewArrayList <Course> ();// Instantiate the List set
  10. }
  11. PublicStudent (String name,IntAge ){// Set the attribute content by constructing
  12. This();// Call construction without Parameters
  13. This. SetName (name );// Set the name attribute content
  14. This. SetAge (age );// Set the age attribute content
  15. }
  16. PublicString getName (){// Obtain the name attribute
  17. ReturnName;
  18. }
  19. Public VoidSetName (String name ){// Set the name attribute
  20. This. Name = name;
  21. }
  22. Public IntGetAge (){// Obtain the age attribute
  23. ReturnAge;
  24. }
  25. Public VoidSetAge (IntAge ){// Set the age attribute
  26. This. Age = age;
  27. }
  28. PublicList <Course> getAllCourses (){// Obtain all courses
  29. ReturnAllCourses;
  30. }
  31. PublicString toString (){// Override the toString () method
  32. Return

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.