Beginner 30 min read

Model a Course Roster

By the end of this lesson, you'll be able to:

  • Write the CourseRoster class holding a List<Student>
  • Add a method to enroll a student into the roster
  • Add a method to report how many students are currently enrolled

Prerequisites: "Model a Student"

Holding a list of students

public class CourseRoster {
    private String courseName;
    private List<Student> enrolledStudents = new List<Student>();

    public CourseRoster(String courseName) {
        this.courseName = courseName;
    }

    public void enroll(Student student) {
        enrolledStudents.add(student);
    }

    public Integer getEnrollmentCount() {
        return enrolledStudents.size();
    }
}

enrolledStudents starts as an empty list the moment a CourseRoster is created, and enroll() grows it one student at a time — the roster owns and protects its own list, exactly like Student protects its own fields.

Putting Student and CourseRoster together

CourseRoster apexBasics = new CourseRoster('Apex Basics');

Student alice = new Student('S001', 'Alice Nkosi', 'alice@example.com');
Student ben = new Student('S002', 'Ben Dlamini', 'ben@example.com');

apexBasics.enroll(alice);
apexBasics.enroll(ben);

System.debug(apexBasics.getEnrollmentCount()); // 2

This is composition (Module 11) in action: CourseRoster has a list of Student objects rather than being one itself — the natural fit, since a roster isn't a kind of student.

Exercise

Add a method listStudentDescriptions() to CourseRoster that returns a List<String> of every enrolled student's describe() output.

Show hint

Loop over enrolledStudents, calling describe() on each, adding to a new List<String>.

APEX

Model a Course Roster Quiz

1. What kind of relationship does CourseRoster have with Student?

Log in to submit the quiz and save your score.

My Notes

Log in to keep private notes on this lesson.

Questions about this lesson

No questions yet — be the first to ask.

Log in to ask a question about this lesson.

Summary

CourseRoster models the second piece from the design sketch — a class that holds a growing collection of Student objects and reports on them.