在Java中,可以通過以下步驟創(chuàng)建類的數(shù)組:
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];
這將創(chuàng)建一個(gè)長度為5的Person類數(shù)組。
for (int i = 0; i < persons.length; i++) {
persons[i] = new Person("Person" + (i+1), 20 + i);
}
這將在循環(huán)中創(chuàng)建5個(gè)Person對象,并將它們存儲在persons數(shù)組中。
完整的代碼示例如下:
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());
}
}
}