如何在 Java 中创建对象数组
什么是对象数组?
Java 对象数组 ,如其名称所定义,存储一个对象数组 .与存储字符串、整数、布尔值等值的传统数组不同,对象数组存储 OBJECTS。数组元素存储对象的引用变量的位置。
语法:
Class obj[]= new Class[array_length]
如何在 Java 中创建对象数组?
步骤 1) 打开您的代码编辑器。
将以下代码复制到编辑器中。
class ObjectArray{
public static void main(String args[]){
Account obj[] = new Account[2] ;
//obj[0] = new Account();
//obj[1] = new Account();
obj[0].setData(1,2);
obj[1].setData(3,4);
System.out.println("For Array Element 0");
obj[0].showData();
System.out.println("For Array Element 1");
obj[1].showData();
}
}
class Account{
int a;
int b;
public void setData(int c,int d){
a=c;
b=d;
}
public void showData(){
System.out.println("Value of a ="+a);
System.out.println("Value of b ="+b);
}
}
步骤 2) 保存您的代码。
保存、编译和运行代码。
步骤 3) Error=?
在进行第 4 步之前尝试调试。
第 4 步) 检查Account obj[] =new Account[2]
这行代码,Account obj[] =new Account[2];完全创建了一个包含两个引用变量的数组,如下所示。
第 5 步) 取消注释行。
取消注释第 4 和 5 行。此步骤创建对象并将它们分配给引用变量数组,如下所示。您的代码现在必须运行。
输出:
For Array Element 0 Value of a =1 Value of b =2 For Array Element 1 Value of a =3 Value of b =4
还要检查:- Java初学者教程
java