Initialization of objects in Java

Source: Internet
Author: User

I have recently looked at the Java programming idea. Some gains. This book is really good.

Initialization in Java is a belief that many people know. However, the specific initialization steps are not necessarily initialized several times. On the Code

 Public classa{ Public StaticA A =NewA ();  Public Static inti;  Public Static intJ= 2;  PublicA () {i++; J++; }        Public Static voidMain (string[] args) {A A1=NewA (); System.out.println ("I =" +a1.i); System.out.println ("J=" +A1.J); }}

What is the result of the output?

2 and 3.

For Java, an automatic initialization action is performed first when the object is constructed. That is initialized to

a=null;i=0;j=0;

Then initialize the default value of the session definition again

A=new A ();

The execution of the constructor here causes i++,j++, and the result

I=1;j=1;

Then assign a value to a, at which point A is not NULL,

And then it's kind of interesting.

Continue with the default initialization of I, because I does not set the default value, so I is still 1, then J because of the default value J becomes 2

i=1;j=2;

Finally in the execution of the constructor i++,j++

Final results

i=2;j=3;

If this particular case of a is removed here can be seen. There are three steps to initialize:

1. Automatically initialized to base type 0, reference type is NULL

2. Set Default values

3. Execute the constructor

Initialization of objects in Java

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.