• Post Reply Bookmark Topic Watch Topic
  • New Topic

Diff b/w explicit in class initialization and non static instance initialization  RSS feed

 
Ben Balach
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi everyone. This is my first post. I come from a C++ background and I recently started learning Java from "Thinking in Java" 4th Edition by Bruce Eckel.

What's the difference between:



and



Thanks in advance to anyone who replies!
 
Tomas Linhart
Ranch Hand
Posts: 86
2
Java Ubuntu VI Editor
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The first approach initializes the fields obj1 and obj2 during their declaration. I guess that's the preferred way when you can initialize them using simple assignment. When you need to initialize the fields with more complex logic, you use the second approach with initializer block. Or you can initialize the fields in constructor. Using initializer block is suitable when you have more constructors that share some common initialization, as the content of initializer block gets copied into each constructor body.

Here it's explained http://docs.oracle.com/javase/tutorial/java/javaOO/initial.html
 
Winston Gutkowski
Bartender
Posts: 10575
66
Eclipse IDE Hibernate Ubuntu
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Tomas Linhart wrote:Using initializer block is suitable when you have more constructors that share some common initialization, as the content of initializer block gets copied into each constructor body...

You know what? I never knew that (probably because I've never used an instance initialiser block); but it's definitely worth a cow.

Winston
 
Tomas Linhart
Ranch Hand
Posts: 86
2
Java Ubuntu VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Winston Gutkowski wrote:You know what? I never knew that (probably because I've never used an instance initialiser block); but it's definitely worth a cow.

Thank you :-) Glad to know that even greenhorns can come up with something interesting ;-)
 
Ashwin Rao
Ranch Hand
Posts: 89
C++ Java Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Whoa! Mind Blown!
Thanks for the info about the initializer blocks!
I would give a cow too if I could! :p
Still thinking about the possiblities!!
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!