This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes Java in General and the fly likes Java Object initializer Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Java Object initializer" Watch "Java Object initializer" New topic

Java Object initializer

Ramesh Pramuditha Rathnayake
Ranch Hand

Joined: Oct 31, 2012
Posts: 169

I've heard that, java object initializer do 3 things in the following order.

1. Initialize non static attributes.
2. Run non static blocks.
3. Run the constructor.

But compiler gives error in following code..

But there is no error in the following code.

What is the reason..?

Campbell Ritchie

Joined: Oct 13, 2005
Posts: 38087
Your informant was mistaken about initialisers running the constructor. That is done by the JVM when the new operator is used. You can find out how it is done in the Java Language Specification (I hope I quoted the right section).
Unlike in the rest of the class, the order of members is significant to initialisers. The field must be declared and definitely assigned before it is available to the initialiser. So your first example, where the initialiser preceded the field, is invalid.
It is sorta covered in the JavaRanch Style Guide.
subject: Java Object initializer
Similar Threads
Am i gone crazy???
Variable scope & life time
Why first of all it runs constructor of class B?
Question on scope
Why there is a compiler error?