Model a Student
By the end of this lesson, you'll be able to:
- Write the Student class with encapsulated fields and a constructor
- Add a method that returns a readable description of a student
- Create and use multiple Student objects
Prerequisites: "Design the Classes"
The Student class
public class Student {
private String studentId;
private String name;
private String email;
public Student(String studentId, String name, String email) {
this.studentId = studentId;
this.name = name;
this.email = email;
}
public String getStudentId() {
return studentId;
}
public String getName() {
return name;
}
public String describe() {
return name + ' (' + studentId + ')';
}
}
This is exactly the encapsulation pattern from Module 11: private fields, set once through the constructor, exposed through controlled public getter methods — nothing outside Student can silently overwrite studentId once it's set.
Creating students
Student alice = new Student('S001', 'Alice Nkosi', 'alice@example.com');
Student ben = new Student('S002', 'Ben Dlamini', 'ben@example.com');
System.debug(alice.describe()); // "Alice Nkosi (S001)"
System.debug(ben.describe()); // "Ben Dlamini (S002)"
Two independent Student objects, each with their own data — exactly the object model from Module 10, now put to real use.
Exercise
Add a getEmail() method to the Student class and create one Student object, debugging their email.
Show hint
public String getEmail() { return email; }
Model a Student Quiz
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
This lesson turns the Student sketch from Lesson 1 into a real class — encapsulated fields, a constructor, and a describe method, exactly as planned.