该楼层疑似违规已被系统折叠 隐藏此楼查看此楼
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. *;
public class School{
private String name ;
private List allStudents ;
public School(){
this.allStudents= new ArrayList() ;
}
public School(String name){
this() ;
this.setName(name) ;
}
public void setName(String name){
this.name= name ;
}
public String getName(){
return this.name;
}
public List getAllStudents(){
return allStudents;
}
public String toString(){
return "学校:" + this.name;
}
}
import java. util. *;
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 iter = sch.getAllStudents().iterator() ;
while(iter.hasNext()){
System.out.println("\t|- " + iter.next()) ;
}
}
};