对象数组

对象数组

对象数组的基本介绍

image-20230412184052011

代码实例

Person类

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

    public Person() {
    }

    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;
    }
}

main方法

public class Demo04 {
    public static void main(String[] args) {
        Person arr[] = new Person[3];//开辟三个地址变量,并没有在堆内存中开辟空间
        Person one = new Person("蔡徐坤", 20);
        Person two = new Person("鹿晗", 25);//这三个才在堆内存中开辟空间
        Person three = new Person("王一博", 26);
        arr[0] = one;
        arr[1] = two;
        arr[2] = three;
        System.out.println("姓名:" + arr[0].getName() + "年龄:" + arr[0].getAge());
        System.out.println("姓名:" + arr[1].getName() + "年龄:" + arr[1].getAge());
        System.out.println("姓名:" + arr[2].getName() + "年龄:" + arr[2].getAge());


    }
}

posted @ 2023-04-12 18:51  harper886  阅读(13)  评论(0编辑  收藏  举报