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 classit can only contain Student objects. Later in the test, after enrolling the second student, allStudents now contains both studentsyou 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




Agile Java. Crafting Code with Test-Driven Development
Agile Javaв„ў: Crafting Code with Test-Driven Development
ISBN: 0131482394
EAN: 2147483647
Year: 2003
Pages: 391
Authors: Jeff Langr

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net