Home > Articles > Programming > Java

  • Print
  • + Share This
This chapter is from the book

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.

02fig04.gif

Figure 2.4 Memory Diagram

  • + Share This
  • 🔖 Save To Your Account