溫馨提示×

java如何創(chuàng)建類的數(shù)組

小億
108
2024-09-26 01:17:59
欄目: 編程語言

在Java中,可以通過以下步驟創(chuàng)建類的數(shù)組:

  1. 定義類:首先需要定義一個(gè)類,例如:
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;
    }
}
  1. 創(chuàng)建類的數(shù)組:接下來可以創(chuàng)建一個(gè)Person類的數(shù)組,例如:
Person[] persons = new Person[5];

這將創(chuàng)建一個(gè)長度為5的Person類數(shù)組。

  1. 初始化數(shù)組元素:可以使用循環(huán)來初始化數(shù)組的每個(gè)元素,例如:
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());
        }
    }
}

0