import java.io.*;
class BankAccount{
private double balance;
public BankAccount(double openingBanlance)
{
balance=openingBanlance;
}
public void deposit(double amount)
{
balance=balance+amount;
}
public void withdraw(double amount)
{
balance=balance-amount;
}
public void display()
{
System.out.println("balance" + balance);
}
}
import java.io.*;
class BankApp{
public static void main(String []args)
{
BankAccount bal[]=new BankAccount[4];
System.out.println(bal[0]);
System.out.println(bal[1]);
System.out.println(bal[2]);
System.out.println(bal[3]);
bal[0]=new BankAccount(100.00);
bal[0].display();
bal[1]=new BankAccount(111.00);
bal[1].display();
System.out.println(bal[0]);
System.out.println(bal[1]);
}
}
1 当只是定义一个大小为4的对象数组时(BankAccount bal[]=new BankAccount[4]),对象数组只是4个引用,并没有内容。所以运行
System.out.println(bal[0]);
System.out.println(bal[1]);
System.out.println(bal[2]);
System.out.println(bal[3]);
得到的结果为:null null null null
为指向空的引用,因为4个引用都没有初始化,指向相应的内存区域。
2
bal[0]=new BankAccount(100.00);
bal[0].display();
bal[1]=new BankAccount(111.00);
bal[1].display();
System.out.println(bal[0]);
System.out.println(bal[1]);
分别初始化 bal[0] bal[1] ,使引用有了指向。
运行结果为:BankAccount@1fb8ee3
BankAccount@61de33
结果分析: 是不是因为引用都是BankAccount数组的,所以指向地址为BankAccount@1fb8ee3
BankAccount@61de33
???