How to define an array of objects in Java?
In Java, you can define an array of objects by following these steps:
- Firstly, it is necessary to define a class for an object. For example, if we want to define a student object, we can create a class called “Student” that includes the attributes and methods of a student.
public class Student {
private String name;
private int age;
// 构造方法
public Student(String name, int age) {
this.name = name;
this.age = age;
}
// 获取姓名
public String getName() {
return name;
}
// 获取年龄
public int getAge() {
return age;
}
}
- Then, an object array can be defined in the main program and each object within the array instantiated. For example, an array of student objects called “students” can be created, containing 3 student objects.
public class Main {
public static void main(String[] args) {
// 定义学生对象数组
Student[] students = new Student[3];
// 实例化学生对象,并添加到数组中
students[0] = new Student("张三", 18);
students[1] = new Student("李四", 19);
students[2] = new Student("王五", 20);
// 遍历学生对象数组,输出每个学生的姓名和年龄
for (int i = 0; i < students.length; i++) {
System.out.println("学生姓名:" + students[i].getName());
System.out.println("学生年龄:" + students[i].getAge());
}
}
}
- Run the program to output the name and age of each student object.
Note: When defining an array of objects, it is necessary to specify the size of the array first, and then access each object in the array using an index.