• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Java Object initializer

 
Ranch Hand
Posts: 178
2
Netbeans IDE MySQL Database Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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..?
 
Marshal
Posts: 79178
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
reply
    Bookmark Topic Watch Topic
  • New Topic