Home  >  Article  >  Java  >  How to create array of objects in Java

How to create array of objects in Java

WBOY
WBOYforward
2023-04-27 12:37:074640browse

1. Concept

The definition of an object array is similar to the definition of a general array, but each element needs to be instantiated.

2. Instance format of object array:

类别名称[]对象数组名称=new类别名称[数组大小]

For example, create an object array of Student class.

Student[] stu = new Student[20];  //创建20个学生对象

3. Example

学生类:
class A{
private String name;
private int 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 test(){
public static void main(String[] args) {
A[] students = new A[2]; //创建2个学生的学生数组
A as= new A();
as.setAge(15);
as.setName(“tom”);
A as1= new A();
as1.setAge(16);
as1.setName(“cat”);
A[] a={as,as1}; //动态创建学生数组
for (A st : a) {//遍历数组
System.out.println(st.getName()+”;”);
}
 
}
 
}

The above is the detailed content of How to create array of objects in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete