Java Reference
In-Depth Information
21 + course2.getNumberOfStudents());
22 }
23 }
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
11 students[numberOfStudents] = student;
12 numberOfStudents++;
13 }
14
15
16
public void
addStudent(String student) {
public
String[] getStudents() {
return
students
return
students;
17 }
18
19
20
public int
getNumberOfStudents() {
number of students
return
numberOfStudents;
21 }
22
23
24
public
String getCourseName() {
return
courseName;
25 }
26
27
28
public void
dropStudent(String student) {
// 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