Home > Java > javaTutorial > body text

How to create array of objects in Java

WBOY
Release: 2023-04-27 12:37:07
forward
4645 people have browsed it

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类别名称[数组大小]
Copy after login

For example, create an object array of Student class.

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

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()+”;”);
}
 
}
 
}
Copy after login

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!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template