java:练习学校学生

做~自己de王妃 提交于 2020-01-22 05:22:59

java:练习学校学生

一个学生对应一个学校

一个学校对应多个学生

Student类,School类,Demo测试类

Student:

public class Student {
	
	private String name;
	private int age;
	private School school;
	
	
	
	
	
	
	public Student() {
		super();
	}

	public Student(String name, int age) {
		
		this.name = name;
		this.age = age;
		
	}

	public String getName() {
		return name;
	}
	
	public void setName(String name) {
		this.name = name;
	}
	
	public int getAge() {
		return age;
	}
	
	public void setAge(int age) {
		this.age = age;
	}

	public School getSchool() {
		return school;
	}

	public void setSchool(School school) {
		this.school = school;
	}
	
	
	public String toString()
	{
		return "学生姓名:"+this.name+",学生年龄"+this.age;
	}
	
	

}

  

School类

public class School {

	private String name;
	private List<Student> allStudents;
	
	
	public School()
	{
		this.allStudents = new ArrayList<Student>();
	}
	
	public School(String name)
	{
		this();
		this.name = name;
	}
	
	public String getName() {
		return name;
	}
	
	public void setName(String name) {
		this.name = name;
	}
	
	public List<Student> getAllStudents() {
		return allStudents;
	}
	
	
	public String toString()
	{
		return "学校信息:" + this.name;
	}
	
	
	
	
}

  

测试;

//一个学生对应一个学校
		//一个学校对应多个学生
		
		School school = new School("zhdzdx");
		Student stu1 = new Student("张三",22);
		Student stu2 = new Student("李四",33);
		Student stu3 = new Student("王五",22);
		school.getAllStudents().add(stu1);
		stu1.setSchool(school);
		school.getAllStudents().add(stu2);
		stu2.setSchool(school);
		school.getAllStudents().add(stu3);
		stu3.setSchool(school);
		System.out.println(school);
		Iterator  iter = school.getAllStudents().iterator();
		while(iter.hasNext())
		{
			Student stu = (Student) iter.next();
			System.out.println(stu);
		}

  

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!