Java Reference
In-Depth Information
10.5 Case Study: Designing the Course Class
This section designs a class for modeling courses.
Key
Point
This topics philosophy is teaching by example and learning by doing . The topic provides a
wide variety of examples to demonstrate object-oriented programming. This section and the
next offer additional examples on designing classes.
Suppose you need to process course information. Each course has a name and has students
enrolled. You should be able to add/drop a student to/from the course. You can use a class to
model the courses, as shown in FigureĀ 10.10.
Course
-courseName: String
-students: String[]
-numberOfStudents: int
The name of the course.
An array to store the students for the course.
The number of students (default: 0).
+Course(courseName: String)
+getCourseName(): String
+addStudent(student: String): void
+dropStudent(student: String): void
+getStudents(): String[]
+getNumberOfStudents(): int
Creates a course with the specified name.
Returns the course name.
Adds a new student to the course.
Drops a student from the course.
Returns the students for the course.
Returns the number of students for the course.
F IGURE 10.10
The Course class models the courses.
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, drop a student from the course using the dropStudent(String student) method,
and return all the students in the course using the getStudents() method. Suppose the Course
class is available; Listing 10.5 gives a test class that creates two courses and adds students to them.
L ISTING 10.5
TestCourse.java
1 public class TestCourse {
2
public static void main(String[] args) {
3
Course course1 = new Course( "Data Structures" );
create a course
4
Course course2 = new Course( "Database Systems" );
5
6 course1.addStudent( "Peter Jones" );
7 course1.addStudent( "Kim 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 = 0 ; i < course1.getNumberOfStudents(); 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 }
add a student
number of students
return students
 
 
 
Search WWH ::




Custom Search