阅读量:0
在Java中,可以通过以下步骤创建类的数组:
- 定义类:首先需要定义一个类,例如:
public class Person { private String name; private int age; public Person(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
- 创建类的数组:接下来可以创建一个Person类的数组,例如:
Person[] persons = new Person[5];
这将创建一个长度为5的Person类数组。
- 初始化数组元素:可以使用循环来初始化数组的每个元素,例如:
for (int i = 0; i < persons.length; i++) { persons[i] = new Person("Person" + (i+1), 20 + i); }
这将在循环中创建5个Person对象,并将它们存储在persons数组中。
完整的代码示例如下:
public class Person { private String name; private int age; public Person(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } } public class Main { public static void main(String[] args) { Person[] persons = new Person[5]; for (int i = 0; i < persons.length; i++) { persons[i] = new Person("Person" + (i+1), 20 + i); } for (int i = 0; i < persons.length; i++) { System.out.println("Name: " + persons[i].getName() + ", Age: " + persons[i].getAge()); } } }