Java User Class Array: Create & Use

To create User objects using an array, first define a User class and then use an array to store multiple User objects. Here is an example:

public class User {
    private String name;
    private int age;

    public User(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }
}

public class Main {
    public static void main(String[] args) {
        // 创建一个包含3个User对象的数组
        User[] users = new User[3];

        // 实例化每个User对象,并将其存储到数组中
        users[0] = new User("Alice", 20);
        users[1] = new User("Bob", 25);
        users[2] = new User("Charlie", 30);

        // 遍历数组并输出每个User对象的信息
        for (User user : users) {
            System.out.println("Name: " + user.getName() + ", Age: " + user.getAge());
        }
    }
}

In the example above, we first defined a User class that includes a constructor with name and age parameters, as well as corresponding getter methods. Then in the Main class, we created an array of User with a length of 3, storing each User object in the array by index. Finally, we used a for-each loop to iterate through the array and output information for each User object.

bannerAds