ခဏလေး ဒီလိုပဲ စဉ်းစားကြည့်
အခုအထိ သင်ခဲ့တဲ့ OOP concepts (class, object, constructor, access modifiers) နဲ့ ArrayList collection ကို ပေါင်းစပ်ပြီး real project တစ်ခု စလုပ်ကြမယ်။ ဒီ project မှာ student information တွေကို manage လုပ်တဲ့ console app ကို 3 parts ခွဲပြီး တည်ဆောက်သွားမှာဖြစ်ပါတယ်။ Part 1 မှာတော့ Student data ကို ကိုယ်စားပြုမယ့် class တစ်ခု design လုပ်ပြီး၊ student list တွေကို သိမ်းထားဖို့ ArrayList structure ကို ပြင်ဆင်ပါမယ်။ Field တွေကို private ထားပြီး encapsulation principle ကို လိုက်နာအောင် ရေးမှာဖြစ်ပါတယ်။
လက်တွေ့ ဆောက်ကြည့်မယ်
Student class တစ်ခုဆောက်ပြီး name (String), id (int), subjectScores (HashMap<String, Integer>) fields သုံးခုထားပါ - field တွေအားလုံးကို private ထားပါ။ Constructor ထဲမှာ name နဲ့ id ကို parameter အနေနဲ့ လက်ခံပြီး subjectScores ကို empty HashMap နဲ့ initialize လုပ်ပါ။ getName() နဲ့ getId() ဆိုတဲ့ public getter methods နှစ်ခု ထည့်ပါ။ StudentManager class ထဲမှာ ArrayList<Student> students field တစ်ခုဆောက်ပြီး main method ထဲမှာ Student object 3 ခု ဆောက်ပြီး list ထဲ add လုပ်ပါ၊ ပြီးရင် enhanced for-loop သုံးပြီး student list တွေကို print ထုတ်ပါ။
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());
}
}
}Console မှာ student list သုံးဦးရဲ့ ID နဲ့ Name တွေကို line တစ်ကြောင်းချင်းစီ print ထုတ်ပေးပါလိမ့်မယ်။၅ မိနစ် စမ်းကြည့်
Student class ထဲမှာ age (int) field ထပ်ထည့်ပြီး constructor နဲ့ getAge() getter method ကို ထပ်ရေးကြည့်ပါ - 5 minutes အတွင်း run ကြည့်ပါ။
သတိလေးတစ်ချက်
Project ကြီးတစ်ခုကို တစ်ခါတည်း ကုန်အောင်မရေးဘဲ Part 1 ရဲ့ structure ကောင်းကောင်း အလုပ်လုပ်ကြောင်း သေချာစစ်ပြီးမှ Part 2 ကို ဆက်သွားပါ။