Creation and initialization of object arrays in Java

Source: Internet
Author: User

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 when simply defining an array of objects of size 4 (BankAccount bal[]=new bankaccount[4]), the object array is just 4 references and has no content. So run

System.out.println (Bal[0]);
System.out.println (bal[1]);
System.out.println (bal[2]);
System.out.println (Bal[3]);

The result is: null NULL NULL

is an empty reference, because 4 references are not initialized and point to the appropriate memory area.

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]);

Initialize bal[0] bal[1, respectively, so that the reference is pointed.

The results of the operation are: Bankaccount@1fb8ee3

Bankaccount@61de33

Result analysis: Is not because references are bankaccount arrays, so point to address as Bankaccount@1fb8ee3

Bankaccount@61de33

。。。


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.