Java class set _ example: one-to-many relationship notes
Instance requirements:
A class set can represent the following relationships: A school can contain multiple students and a student belongs to one school. This is a typical one-to-many relationship, in this case, you can use the class set to represent the relationship.
3. Knowledge Used in this instance
1. Class Design
2. Class Set
4. Details
If a school has multiple students, the number of students is unknown, so it cannot be represented by an ordinary array of objects. Therefore, it must be represented by a class set.
Code:
School. Java
Import Java. util. list; import Java. util. arraylist; public class school {private string name; private list <student> allstudents; Public School () {This. allstudents = new arraylist <student> ();} Public School (string name) {this (); this. setname (name);} public void setname (string name) {This. name = Name;} Public String getname () {return this. name;} public list <student> getallstudents () {return this. allstudents;} Public String tostring () {return "school name:" + this. name ;}}
Student. Java
Public class student {private string name; private int age; private school; // a student belongs to a school public student (string name, int age) {This. setname (name); this. setage (AGE);} public void setschool (school School) {This. school = school;} public school getschool () {return this. school;} public void setname (string name) {This. name = Name;} public void setage (INT age) {This. age = age;} Public String getname () {return this. name;} public int getage () {return this. age;} Public String tostring () {return "Student name:" + this. name + "; age:" + this. age ;}};
Testdemo. Java
Import Java. util. iterator; public class testdemo {public static void main (string [] ARGs) {SCHOOL Sch = New School ("Tsinghua University"); Student S1 = new student ("James ", 21); Student S2 = new student ("Li Si", 22); Student S3 = new student ("Wang Wu", 23); Sch. getallstudents (). add (S1); Sch. getallstudents (). add (S2); Sch. getallstudents (). add (S3); s1.setschool (Sch); s2.setschool (Sch); s3.setschool (Sch); system. out. print (Sch); iterator <student> iter = Sch. gerallstudents (). iterator (); While (ITER. hasnext () {system. out. println ("\ t |-" + ITER. next ());}}}
5. Summary
1. Understand the relationship between class sets, so this relationship will be referred to as a standard in the futureProgram.