对象数组 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) 检查账户 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


