在Java中,可以通過以下步驟來創(chuàng)建對(duì)象數(shù)組:
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]; // 創(chuàng)建包含5個(gè)元素的對(duì)象數(shù)組
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);
這樣就創(chuàng)建了一個(gè)包含5個(gè)學(xué)生對(duì)象的數(shù)組。
完整示例代碼如下:
public class Main {
public static void main(String[] args) {
Student[] students = new Student[5]; // 創(chuàng)建包含5個(gè)元素的對(duì)象數(shù)組
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);
// 遍歷數(shù)組并輸出每個(gè)學(xué)生的信息
for (Student student : students) {
System.out.println("Name: " + student.getName() + ", Age: " + student.getAge());
}
}
}
運(yùn)行以上代碼將輸出:
Name: Alice, Age: 18
Name: Bob, Age: 19
Name: Charlie, Age: 20
Name: Dave, Age: 21
Name: Eve, Age: 22