在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[] 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());
}
}
}