Java Reference
In-Depth Information
Number of students in course1: 3
Peter Jones, Kim Smith, Anne Kennedy,
Number of students in course2: 2
The Course class is implemented in Listing 10.6. It uses an array to store the students in the
course. For simplicity, assume that the maximum course enrollment is 100 . The array is cre-
ated 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 12). The getStudents method returns the array. The dropStudent method (line 27)
is left as an exercise.
L ISTING 10.6
Course.java
1 public class Course {
2
private String courseName;
3
private String[] students = new String[ 100 ];
create students
4
private int numberOfStudents;
5
6
public Course(String courseName) {
add a course
7
this .courseName = courseName;
8 }
9
10 public void addStudent(String student) {
11 students[numberOfStudents] = student;
12 numberOfStudents++;
13 }
14
15
public String[] getStudents() {
return students
16
return students;
17 }
18
19
public int getNumberOfStudents() {
number of students
20
return numberOfStudents;
21 }
22
23
public String getCourseName() {
24
return courseName;
25 }
26
27
public void dropStudent(String student) {
28
// Left as an exercise in Programming Exercise 10.9
29 }
30 }
The array size is fixed to be 100 (line 3), so you cannot have more than 100 students in the
course. You can improve the class by automatically increasing the array size in Programming
Exercise 10.9.
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.
The user can create a Course object and manipulate it through the public methods
addStudent , dropStudent , getNumberOfStudents , and getStudents . However, the
user doesn't need to know how these methods are implemented. The Course class encapsu-
lates the internal implementation. This example uses an array to store students, but you could
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.
 
 
Search WWH ::




Custom Search