在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