• Post Reply Bookmark Topic Watch Topic
  • New Topic

Difference between instance block's variable initialization and constructor variable initialization  RSS feed

 
Ranch Hand
Posts: 118
Android Java Objective C
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi

Instance block which are dependent on object creation can initialize instance variable just like how the constructor can also initialize instance variable's. What is the difference between both.

Thanks
 
Greenhorn
Posts: 7
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The main difference is the execution sequence. An initialization block is always executed before the constructor. Here is an example:





Here are the outputs I obtained:

initialization
constructor
James Brown
initialization
default constructor
null Dean




 
Sheriff
Posts: 4931
334
BSD
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Great answer, have a cow Dominique Ubersfeld and welcome to the Ranch
 
krishnadhar Mellacheruvu
Ranch Hand
Posts: 118
Android Java Objective C
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you Dominique
 
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dominique Ubersfeld wrote:The main difference is the execution sequence. An initialization block is always executed before the constructor.


Two further clarifications. One. If the constructor has a call to super(), or even with a defaulted call, then the instance initializer is executed after the super() call, but before the main body of the constructor. And two. All instance initializers are *always* called during instantiation -- whereas the constructor can be avoided, by using an overloaded constructor.

Henry
 
Marshal
Posts: 56600
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch again.
I would have thought that the biggest difference is that you pass a parameter to the constructor, and this allows more variability of states of the objects.

By the way: who told you that line 12 is a default constructor? They were mistaken. It isn't a default constructor.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!