在Java中,可以通過以下步驟來創建對象數組:
public class Student {
private String name;
private int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
// 省略其他方法和屬性的定義
}
Student[] students = new Student[5]; // 創建包含5個元素的對象數組
students[0] = new Student("Alice", 18);
students[1] = new Student("Bob", 19);
students[2] = new Student("Charlie", 20);
students[3] = new Student("Dave", 21);
students[4] = new Student("Eve", 22);
這樣就創建了一個包含5個學生對象的數組。
完整示例代碼如下:
public class Main {
public static void main(String[] args) {
Student[] students = new Student[5]; // 創建包含5個元素的對象數組
students[0] = new Student("Alice", 18);
students[1] = new Student("Bob", 19);
students[2] = new Student("Charlie", 20);
students[3] = new Student("Dave", 21);
students[4] = new Student("Eve", 22);
// 遍歷數組并輸出每個學生的信息
for (Student student : students) {
System.out.println("Name: " + student.getName() + ", Age: " + student.getAge());
}
}
}
運行以上代碼將輸出:
Name: Alice, Age: 18
Name: Bob, Age: 19
Name: Charlie, Age: 20
Name: Dave, Age: 21
Name: Eve, Age: 22