Let's Think This Through
Let's combine the OOP concepts you've learned so far (class, object, constructor, access modifiers) with the ArrayList collection and start a real project. We'll build a console app for managing student information, split into 3 parts. In Part 1, we'll design a class to represent Student data and set up an ArrayList structure to hold the student list. We'll keep the fields private, following the encapsulation principle.
Let's Build It
Build a Student class with three fields: name (String), id (int), and subjectScores (HashMap<String, Integer>) — make all of them private. In the constructor, accept name and id as parameters and initialize subjectScores as an empty HashMap. Add two public getter methods, getName() and getId(). In the StudentManager class, create an ArrayList<Student> students field, then in the main method create 3 Student objects, add them to the list, and use an enhanced for-loop to print out the student list.
Sample Code
import java.util.ArrayList;
import java.util.HashMap;
class Student {
private String name;
private int id;
private HashMap<String, Integer> subjectScores;
public Student(String name, int id) {
this.name = name;
this.id = id;
this.subjectScores = new HashMap<>();
}
public String getName() {
return name;
}
public int getId() {
return id;
}
}
public class StudentManager {
public static void main(String[] args) {
ArrayList<Student> students = new ArrayList<>();
students.add(new Student("Aung Aung", 101));
students.add(new Student("Su Su", 102));
students.add(new Student("Ko Ko", 103));
for (Student s : students) {
System.out.println("ID: " + s.getId() + " - Name: " + s.getName());
}
}
}The console will print the ID and Name of three students, one per line.5-Minute Try-It
Add an age (int) field to the Student class, plus a constructor update and a getAge() getter method — try running it within 5 minutes.
A Quick Word of Caution
Don't try to write the whole big project in one go. Make sure Part 1's structure works properly first, then move on to Part 2.