java中的关联

首先,明确几个要点:

1.每个类中必有成员变量(或局部变量)和构造方法以及该类的其他行为方法

2.java是面向对象的编程语言,即:先创建类,然后在main方法中创建对象,然后根据对象调用方法。

 

以下是我学习过程中的代码:

前提要点分析:

学生与课程之间的关系就是:

一个课程对应多个学生,一个学生对应多个课程。

本代码做的就是:将每个课程对应的学生 以及 每个学生对应的课程 关联起来。

 

课程类:

点击查看代码
public class Course {
	int number;// 课程号

	String name;// 课程名称

	private Student[] classList;

	int StudentCount;// 学生人数

	Course(String name, int id) {
		this.number = id;
		this.name = name;
		StudentCount = 0;
		classList = new Student[10];
	}

	public Student[] getClassList() {
		return classList;
	}

	public int getStudentCount() {
		return StudentCount;
	}

	public int getNumber() {
		return number;
	}

	public String getName() {
		return name;
	}

	public void addStudent(Student s) {
		classList[StudentCount++] = s;
	}
}

 

学生类:

点击查看代码
public class Student {
	public String name;

	public int number;

	private Course[] courseList;

	public int courseCount;
	
	public Student(int number,String name) {
		this.number = number;
		this.name = name;
		courseCount =0;
		courseList = new Course[10];
	}
	public void addCourse(Course c) {
		courseList[courseCount++]=c;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getNumber() {
		return number;
	}
	public void setNumber(int number) {
		this.number = number;
	}
	public Course[] getCourseList() {
		return courseList;
	}
	public void setCourseList(Course[] courseList) {
		this.courseList = courseList;
	}
	public int getCourseCount() {
		return courseCount;
	}
	public void setCourseCount(int courseCount) {
		this.courseCount = courseCount;
	}

}

 

测试类:用来使用main方法:

点击查看代码
public class Test {

	public static void main(String[] args) {
		Course c1 = new Course("语文", 1);
		Course c2 = new Course("数学", 2);
		Course c3 = new Course("英语", 3);

		Student s1 = new Student(21072134, "张三");
		Student s2 = new Student(20172135, "李四");

		s1.addCourse(c1);
		s1.addCourse(c3);
		s2.addCourse(c3);
		s2.addCourse(c2);
		c1.addStudent(s1);
		c2.addStudent(s2);
		c3.addStudent(s2);
		c3.addStudent(s1);
		
		System.out.println("课程"+c1.number+c1.name+"的学生数:"+c1.getStudentCount());
		System.out.println("课程"+c2.number+c2.name+"的学生数:"+c2.getStudentCount());
		System.out.println("课程"+c3.number+c3.name+"的学生数:"+c3.getStudentCount());
		System.out.println(s1.number+s1.name+"的课程数:"+s1.getCourseCount());
		System.out.println(s2.number+s2.name+"的课程数:"+s2.getCourseCount());
	}

}

 

上一篇:C++多线程5


下一篇:mysql基础练习题19题