This section uses the Course class to demonstrate the creation and use of classes. The UML diagram for the class is shown in Figure 7.25.
A Course object can be created using the constructor Course(String name ) by passing a course name. You can add students to the course using the addStudent (String student) method and return all the students for the course using the getStudents() method. Suppose the class is available, Listing 7.10 gives a test class that creates two courses and adds students to the courses.
1 public class TestCourse { 2 public static void main(String[] args) { 3 Course course1 = new Course( "Data Structures" ); 4 Course course2 = new Course( "Database Systems" ); 5 6 course1.addStudent( "Peter Jones" ); 7 course1.addStudent( "Brian Smith" ); 8 course1.addStudent( "Anne Kennedy" ); 9 10 course2.addStudent( "Peter Jones" ); 11 course2.addStudent( "Steve Smith" ); 12 13 System.out.println( "Number of students in course1: " 14 + course1.getNumberOfStudents() ); 15 String[] students = course1.getStudents() ; 16 for ( int i = ; i < course1.getNumberoffStudent() ; i++) 17 System.out.print(students[i] + ", " ); 18 19 System.out.println(); 20 System.out.print( "Number of students in course2: " 21 + course2.getNumberOfStudents()); 22 } 23 } |
The Course class is implemented in Listing 7.11. The Course class uses an array to store the students for the course. For simplicity, assume that the maximum course enrollment is 100 . The array is created using new String[100] in line 3. The addStudent method (line 10) adds a student to the array. Whenever a new student is added to the course, numberOfStudents is increased (line 11). The getStudents method returns the array.
1 public class Course { 2 private String name; 3 private String[] students = new String[ 100 ] 4 private int numberOfStudents; 5 6 public Course(String name) { 7 this .name = name; 8 } 9 10 public void addStudent(String student) { 11 students[numberOfStudents] = student; 12 numberOfStudents++; 13 } 14 15 public String[] getStudents() { 16 return students; 17 } 18 19 public int getNumberOfStudents() { 20 return numberOfStudents; 21 } 22 23 public String getName() { 24 return name; 25 } 26 } |
The array size is fixed in Listing 7.11. You can improve it to automatically increase the array size in Exercise 7.8.
Note
When you create a Course object, an array object is created. A Course object contains a reference to the array. For simplicity, you can say that the Course object contains the array. |
Note
The user can create a Course and manipulate it through the public methods addStudent , getNumberOfStudents , and getStudents . However, the user doesn't need to know how these methods are implemented. The Course class encapsulates the internal implementation. This example uses an array to store students. You may use a different data structure to store students. The program that uses Course does not need to change as long as the contract of the public methods remains unchanged. |