Win a copy of Java 9 Revealed this week in the Features new in Java 9 forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

question on Boyarsky & Selikoff book page 19  RSS feed

 
Patrick Cicero
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I understand the concept of running field and instance initialzer blocks are run.

What I am confused about is what running instance initializer blocks
The code at line 3 is {System.out.println("setting field");} I see that as a code block but not sure what you mean by "an instance initializer block"



 
Roel De Nijs
Sheriff
Posts: 11077
173
AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here's an example illustrating both static and instance initializer blocks:

Output:
I'm a static init block
I'm a static init block too
begin main
I'm an instance init block
I'm an instance init block as well
I'm an instance init block
I'm an instance init block as well
end main


Hope it helps!
Kind regards,
Roel
 
Patrick Cicero
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank You very much was too hung up on the code and did not step back to think the events
1) Class loaded
2) Static Blocks run (belong to class)
3) main run
4) main instantiates 2 instances of class causing instance block to be run

 
Roel De Nijs
Sheriff
Posts: 11077
173
AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And if you want a more complex example (with class and instance variables), check out this thread.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!