Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Java Object initializer

 
Ramesh Pramuditha Rathnayake
Ranch Hand
Posts: 178
2
Java MySQL Database Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Sheriff
Pie
Posts: 50206
79
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic