מחלקה לדוגמה – Student
בכל הדוגמאות נשתמש במחלקה פשוטה:
public class Student { private String name; private int grade; public Student(String name, int grade) { this.name = name; this.grade = grade; } public String getName() { return name; } public int getGrade() { return grade; } public void setGrade(int g) { grade = g; } }
יצירת מערך של עצמים
// שלב 1: יצירת המערך (כל התאים הם null!) Student[] students = new Student[3]; // שלב 2: אתחול כל תא בנפרד students[0] = new Student("דני", 85); students[1] = new Student("רונה", 92); students[2] = new Student("משה", 78);
חשוב! אחרי new Student[3] כל התאים הם null. חובה ליצור כל עצם בנפרד.
מעבר על מערך של עצמים
// הדפסת כל התלמידים for (int i = 0; i < students.length; i++) { System.out.println(students[i].getName() + ": " + students[i].getGrade()); }
פעולות נפוצות
מציאת תלמיד עם הציון הגבוה ביותר
public static Student bestStudent(Student[] arr) { Student best = arr[0]; for (int i = 1; i < arr.length; i++) { if (arr[i].getGrade() > best.getGrade()) best = arr[i]; } return best; }
ספירת תלמידים שעומדים בתנאי
public static int countPassing(Student[] arr) { int count = 0; for (int i = 0; i < arr.length; i++) { if (arr[i].getGrade() >= 56) count++; } return count; }
חיפוש תלמיד לפי שם
public static Student findByName(Student[] arr, String name) { for (int i = 0; i < arr.length; i++) { if (arr[i].getName().equals(name)) return arr[i]; } return null; // לא נמצא }
בניית מערך עצמים לפי תנאי
public static Student[] getPassingStudents(Student[] arr) { // מעבר 1: ספירה int count = 0; for (int i = 0; i < arr.length; i++) { if (arr[i].getGrade() >= 56) count++; } // מעבר 2: מילוי Student[] result = new Student[count]; int idx = 0; for (int i = 0; i < arr.length; i++) { if (arr[i].getGrade() >= 56) { result[idx] = arr[i]; idx++; } } return result; }
שאלות נפוצות
למה המערך מתחיל עם null בכל התאים?
כי new Student[3] יוצר מערך של הפניות (references), לא עצמים. ברירת המחדל של הפנייה היא null. צריך ליצור כל עצם בנפרד עם new.
מה זה NullPointerException?
חריג שנזרק כשמנסים לגשת לפעולה או שדה של null. למשל, אם students[2] הוא null ומנסים students[2].getName().
האם אפשר לשים עצמים מסוגים שונים באותו מערך?
לא במערך רגיל – כל האיברים חייבים להיות מאותה מחלקה (או תת-מחלקה שלה, אם יש ירושה).
צריכים עזרה עם תכנות מונחה עצמים?
מורים פרטיים ילמדו אתכם מחלקות, עצמים ומערכים ב-Java.
מצאו מורה פרטי