Java 中的对象数组
Java 中的对象数组是什么?
Java 对象数组,顾名思义,存储的是对象数组。与存储字符串、整数、布尔值等值的传统数组不同,对象数组存储的是对象。数组元素存储对象引用变量的位置。
语法
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) 错误=?
在继续第 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


