实例要求
使用类集可以表示出以下的关系:一个学校可以包含多个学生,一个学生属于一个学校,那么这就是一个典型的一对多关系,此时就可以通过类集进行关系的表示。
实例主要采用的知识
1、类的设计
2、类集
一个学校有多个学生,那么学生的个数属于未知的,那么这样一来肯定无法用普通的对象数组表示。所以,必须通过类集表示。
学生类:
public class Student{
private String name ;
private int age ;
private School 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 "学生姓名:" + this.name + ";年龄:" + this.age ;
}
};
学校类:
- 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 "学校名称:" + this.name ;
- }
- };
- import java.util.Iterator ;
- public class TestDemo{
- public static void main(String args[]){
- School sch = new School("清华大学") ; // 定义学校
- Student s1 = new Student("张三",21) ;
- Student s2 = new Student("李四",22) ;
- Student s3 = new Student("王五",23) ;
- sch.getAllStudents().add(s1) ;
- sch.getAllStudents().add(s2) ;
- sch.getAllStudents().add(s3) ;
- s1.setSchool(sch) ;
- s2.setSchool(sch) ;
- s3.setSchool(sch) ;
- System.out.println(sch) ;
- Iterator<Student> iter = sch.getAllStudents().iterator() ;
- while(iter.hasNext()){
- System.out.println("\t|- " + iter.next()) ;
- }
- }
- };
总结:
1、明白类集的关系,那么这种关系将成为日后标准程序的开发基础