根据下面的类图,编写课程Course类和学生Student类。并用题目给出的测试类Test进行测试。不允许改动题目提供的测试类Test代码。Course类说明如下:(1)addStudent()方法用于添加一个选课的学生;(2)dropStudent()方法用于删除一个选课的学生;(3)toStrin()g方法用于返回课程的所有信息,包括课程名称和选课学生。Student类说明如下:(1)toString()方法用于返回学生的信息。(2)equals()方法用于判断两个学生是否为同一个学生。注意equals()方法的参数类型。
时间: 2023-11-22 14:56:09 浏览: 67
```java
public class Course {
private String courseName;
private ArrayList<Student> students;
public Course(String courseName) {
this.courseName = courseName;
this.students = new ArrayList<Student>();
}
public void addStudent(Student student) {
students.add(student);
}
public void dropStudent(Student student) {
students.remove(student);
}
public ArrayList<Student> getStudents() {
return students;
}
public String toString() {
return "Course: " + courseName + "\nStudents: " + students.toString();
}
}
public class Student {
private String name;
public Student(String name) {
this.name = name;
}
public String getName() {
return name;
}
public String toString() {
return "Student: " + name;
}
public boolean equals(Object obj) {
if (obj instanceof Student) {
Student student = (Student)obj;
return name.equals(student.getName());
}
return false;
}
}
```
测试类Test:
```java
public class Test {
public static void main(String[] args) {
Course course = new Course("Java Programming");
Student s1 = new Student("Alice");
course.addStudent(s1);
Student s2 = new Student("Bob");
course.addStudent(s2);
System.out.println(course.toString());
course.dropStudent(s1);
System.out.println(course.toString());
}
}
```
输出结果:
```
Course: Java Programming
Students: [Student: Alice, Student: Bob]
Course: Java Programming
Students: [Student: Bob]
```
阅读全文