- CourseSession
- Enrolling Students
- int
- Initialization
- Default Constructors
- Suites
- The SDK and java.util.ArrayList
- Adding Objects
- Incremental Refactoring
- Objects in Memory
- Packages and the import Statement
- The java.lang Package
- The Default Package and the package Statement
- The setUp Method
- More Refactoring
- Class Constants
- Dates
- Overloaded Constructors
- Deprecation Warnings
- Refactoring
- Creating Dates with Calendar
- Comments
- Javadoc Comments
- Exercises
Objects in Memory
In testEnrollStudents, you send the getAllStudents message to session and store the result in a java.util.ArrayList reference that is bound to the Student class—it can only contain Student objects. Later in the test, after enrolling the second student, allStudents now contains both students—you don't need to ask the session object for it again.
public void testEnrollStudents() { CourseSession session = new CourseSession("ENGL", "101"); Student student1 = new Student("Cain DiVoe"); session.enroll(student1); assertEquals(1, session.getNumberOfStudents()); java.util.ArrayList<Student> allStudents = session.getAllStudents(); assertEquals(1, allStudents.size()); assertEquals(student1, allStudents.get(0)); Student student2 = new Student("Coralee DeVaughn"); session.enroll(student2); assertEquals(2, session.getNumberOfStudents()); assertEquals(2, allStudents.size()); assertEquals(student1, allStudents.get(0)); assertEquals(student2, allStudents.get(1)); }
The reason is illustrated in Figure 2.4. The CourseSession object holds on to the students field as an attribute. This means that the students field is available throughout the lifetime of the Course-Session object. Each time the getNumberOfStudents message is sent to the session, a reference to the very same students field is returned. This reference is a memory address, meaning that any code using the reference ends up at the same memory location at which the students field is stored.
Figure 2.4 Memory Diagram