《JAVA继承与多态》改写程序清单10-6中的Course类,编写一个测试类测试所有的方法

JAVA实验《继承与多态》【课程类Course】改写程序清单10-6中的Course类。 使用ArrayList代替数组来存储学生。不应该改变Course类的原始合约(即不要改变构造方法和方法的方法头定义,包括返回类型、方法名及参数列表,但私有的成员可以改变)。最后编写一个测试类测试所有的方法。
程序清单10-6
public class Course {
private String courseName;
private String[] students = new String[100];
private int numberOfStudents;

public Course(String courseName) {
this.courseName = courseName;
}

public void addStudent(String student) {
students[numberOfStudents] = student;
numberOfStudents++;
}

public String[] getStudents() {
return students;
}

public int getNumberOfStudents() {
return numberOfStudents;
}

public String getCourseName() {
return courseName;
}

public void dropStudent(String student) {
// Left as an exercise in Exercise 9.9
}

}

解决方案:
//修改方法
package shiyan52;

import java.util.ArrayList;

public class Course {

  private String courseName;
  ArrayList students = new ArrayList<>();//改写数组的创建方法      
  private int numberOfStudents;

  public Course(String courseName) {
        this.courseName = courseName;
  }   //不需要改
  public String getCourseName(){  
        return courseName;  
  }   //不需要改

  public void addStudents(String student){  
        students.add(student);  
  }  //修改添加元素的方法:使用ArrayList方法修改掉数组方法
  public ArrayList getStudents() {
        return students;
  }
  public void dropStudent(String student) {
      students.remove(student);// Left as an exercise in Exercise 9.9
                               //JAVA 动态拓展数组 落实dropStudent 新增clear() 清除所有元素(学生)的功能
      }

  public void clear(){  
        students.clear();  
    }  

}

//测试类
package shiyan52;

import java.util.ArrayList;

public class TestCourse {
public static void main(String[] args) {
Course course1 = new Course(“Data Structures”);
Course course2 = new Course(“Database Systems”);

        course1.addStudents("Peter Jones");
        course1.addStudents("Brian Smith");
        course1.addStudents("Anne Kennedy");

        course2.addStudents("Peter Jones");
        course2.addStudents("Steve Smith");

        System.out.println("Number of students in course1: "
          + course1.getNumberOfStudents()+"and they are:"); 

        ArrayList students1 = course1.getStudents();
          System.out.println(course1.students + ", ");    

        System.out.println("Number of students in course2: "
                  + course2.getNumberOfStudents()+"and they are:");

        ArrayList students2 = course2.getStudents();
          System.out.println(course1.students + ", ");

       (course1.students).clear();
       (course2.students).clear();
       System.out.println("清除courses1,course2 中的学生后两门课程中人数为"+
          course1.getNumberOfStudents()+"、"+
          course2.getNumberOfStudents()+".");
 }     

}

//输出结果:
《JAVA继承与多态》改写程序清单10-6中的Course类,编写一个测试类测试所有的方法_第1张图片

你可能感兴趣的:(JAVA初学实验心得)