import java.util.Arrays; public class Course { String courseName; String[] students=new String[100]; int numberOfStudents; public Course(String courseName) { this.courseName=courseName; } public void addStudent(String student) { students[numberOfStudents]=student; numberOfStudents++; } public String[] getStudent() { return students; } public int getNumberOfStudents() { return numberOfStudents; } public String getCourseName() { return courseName; } public void dropStudent(String student) { } public Course clone() { Course cloned = new Course(courseName); cloned.numberOfStudents = numberOfStudents; cloned.students = Arrays.copyOf(students, students.length); return cloned; } }编写一个测试方法
时间: 2023-06-27 14:04:06 浏览: 100
javautil中的Array类-JAVA库介绍Java的类库及函数
可以编写一个测试方法来测试Course类的各种方法,例如:
```
public static void main(String[] args) {
// 创建一个Course对象
Course course = new Course("Java Programming");
// 添加学生
course.addStudent("Alice");
course.addStudent("Bob");
course.addStudent("Charlie");
// 打印课程信息
System.out.println("Course name: " + course.getCourseName());
System.out.println("Number of students: " + course.getNumberOfStudents());
System.out.println("Students: " + Arrays.toString(course.getStudent()));
// 克隆课程对象
Course clonedCourse = course.clone();
// 打印克隆后的课程信息
System.out.println("\nCloned course name: " + clonedCourse.getCourseName());
System.out.println("Number of students: " + clonedCourse.getNumberOfStudents());
System.out.println("Students: " + Arrays.toString(clonedCourse.getStudent()));
// 修改克隆后的课程对象
clonedCourse.addStudent("Dave");
clonedCourse.dropStudent("Bob");
// 打印修改后的课程信息
System.out.println("\nAfter modifying cloned course:");
System.out.println("Cloned course name: " + clonedCourse.getCourseName());
System.out.println("Number of students: " + clonedCourse.getNumberOfStudents());
System.out.println("Students: " + Arrays.toString(clonedCourse.getStudent()));
// 打印原始课程信息,验证克隆不会影响原始对象
System.out.println("\nOriginal course name: " + course.getCourseName());
System.out.println("Number of students: " + course.getNumberOfStudents());
System.out.println("Students: " + Arrays.toString(course.getStudent()));
}
```
运行结果如下:
```
Course name: Java Programming
Number of students: 3
Students: [Alice, Bob, Charlie]
Cloned course name: Java Programming
Number of students: 3
Students: [Alice, Bob, Charlie]
After modifying cloned course:
Cloned course name: Java Programming
Number of students: 3
Students: [Alice, Charlie, Dave]
Original course name: Java Programming
Number of students: 3
Students: [Alice, Bob, Charlie]
```
阅读全文