Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Instance Block vs Constructor

 
Arun C. Giridharan
Ranch Hand
Posts: 96
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can anyone say the difference between Instance block and constructor.....they bothr use to intialize .....see the following code


....actually constructor is used to instialize the value 0 ...for instance variables right!...as in above example wen value is intialized through instance block ...in constructor those must (instance variable)...must again set back to 0...right! .....javascript:emoticon('');

EDIT: Code Tags - JD
 
Janeice DelVecchio
Saloon Keeper
Posts: 1809
12
Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to JavaRanch!

Try to remember to use code tags when you post.... it will help folks to read what you've posted

Since you're new, and I'm incredibly handy, I'll go ahead and add them for you
 
Campbell Ritchie
Sheriff
Pie
Posts: 48953
60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
By "instance block" I presume you mean "instance initializer". A constructor can have parameters passed to it, and is probably a better way to initialise the values so as to establish the class invariant. Have look at the Java™ Language specification about initializers and constructors (1) and maybe (2).
 
John Pacuta
Greenhorn
Posts: 20
1
Android Java Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Say I wanted an object to print to the console something that the user defines. I will show how I would do that using an instance initialization block and with a constructor and then explain the difference.

1) With an instance initialization block

2) With a constructor


These code blocks are missing a main method and need a method extraction for the printing method BUT writing them helped me think about instance method vs. constructor. Basically, using a constructor gives me more control over how I assign what is being passed into my object. The instance initialization block allows me to use values in an object. The constructor allows an object to inherit values when it is created. The difference is in how the values are passed in. Are they passed in when the object is created from an outside source (constructor) or do they already exist within the class (instance)? For more information, I found this article online: http://www.thejavageek.com/2013/07/21/initialization-blocks-constructors-and-their-order-of-execution/
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15281
39
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
John, your first example does not compile. You cannot put arbitrary statements at class level - lines 8, 9 and 10 are not allowed at class level. Did you mean to put them inside the instance initializer block?
 
Campbell Ritchie
Sheriff
Pie
Posts: 48953
60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
John Pacuta wrote:. . . how I would do that using an instance initialization block and with a constructor and then explain the difference. . . .
I would hope you don't use an initialiser nor a constructor to print output to the screen. You might use print statements for debugging but printing output usually belongs inside methods rather than initialisers.
 
John Pacuta
Greenhorn
Posts: 20
1
Android Java Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
@ Jesper and Campbell

Thank you so much for your replies. I could sense that code had smells but I posted it to contribute. The truth is I don't really understand the concept and difference between instance initializers and constructors and when and where to use them. That information about class level statements not encapsulated in a method, haha I should know that! Is it wrong to post crumby code?
 
Henry Wong
author
Marshal
Pie
Posts: 21117
78
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

In my opinion, and on one hand, both constructors and instance initializers are used for initialization of the object -- and having more than one way to do it can lead to confusion.


However, on the other hand, perhaps you want the initialization code nearer (source location) to the declaration of the instance variable. And this may be hard to do with constructors, especially if you have many constructors. Also, instance initializers are always executed when an instance is created. With constructors, it may (or may not) be executed, depending on what constructors are called.

Henry
 
Campbell Ritchie
Sheriff
Pie
Posts: 48953
60
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I don't like initialisers myself, but others may disagree. You should have as few constructors as possible (note a special use of constructors in the Java® Language Specification); that means anybody instantiating the class must provide the requisite constructor arguments. Make sure every constructor call initialises every instance field (not static fields which should be initialised differently). Remember you can use the this(...); idiom to call several constructors.

Naughty and mischievous trick:- Mark every instance field final. Compile the class. Ignore the compiler errors about field XYZ is final cannot be reassigned. Look for might not have been initialised compiler errors. If any such errors appear for your instance fields, then there is a path through a constructor which does not initialise that field. Then you know to correct that error. Once you have got rid of every might not be initialised error, you can take the final markers off again
 
Mike. J. Thompson
Bartender
Posts: 689
17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Personally I would say to leave the final modifiers there unless you actually need to mutate the field, especially after going to the effort to add them in

Out of interest, why don't you like instance initializer blocks Campbell?
 
Tim Holloway
Saloon Keeper
Pie
Posts: 18156
53
Android Eclipse IDE Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Effectively, the Java compiler collects all the initialization code in a class definition - whether it's single-statement items or blocks and concatenates them to form an anonymous super-constructor (decompiled code may show this method as "_init()").

When a class object is instantiated, first the VM allocates memory to hold the class resources - both the visible ones, such as instance variables, and the invisible ones (general overhead) and the inherited ones. At that point they are all blank. Then the methods of its superclass are invoked, initializing the inherited items. Then the "_init()" method is invoked, performing the statement and block init code. Then the explicit constructor is invoked, which in turn may invoke other super or local constructors (in that order).

A lot of times, I'll code an explicit method named "init()" that the constructor(s) can invoke. This is handy in cases where there's common code but nothing that one constructor can invoke from another constructor. And it's also very useful for re-usable objects, because I can recycle them by invoking init() without actually having to construct a whole whole instance (which I might not be able to link into existing operations).

Whether I code initialization statements or do it in explicit methods (constructor and/or init()) depends a lot on usage. Sometimes I want no ambiguity about an item's initial value - keeping the value and type definition visibly paired, so I'll code a direct assignment. Other times, the initial value may depend on context and/or I might want to re-init() it. Init blocks I do less often, and it's usually something I do when a simple statement isn't enough to initialize a value. For example, if I need to locate an external service first.
 
Campbell Ritchie
Sheriff
Pie
Posts: 48953
60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Mike. J. Thompson wrote:. . . Out of interest, why don't you like instance initializer blocks Campbell?
What is the point to them? If you are going to initialise a field to a default value every time, it is possible to do that in the constructor, or with a declaration‑and‑initialisation combined. There are also possible problems about order of execution with initialisers, which I read about in Java Puzzlers by Bloch and Gafter, but I have forgotten the details.

Now, static initialisers have the same risks about execution order if they are multiple, but if you only have one static initialiser which runs when the class is loaded (therefore before any constructors), then that is perfectly all right and if initialisation is complicated, probably the best way to initialise a static field.
 
Campbell Ritchie
Sheriff
Pie
Posts: 48953
60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Mike. J. Thompson wrote:Personally I would say to leave the final modifiers there . . .
Good point. I know Winston G would agree with you there.
 
Joe Bishara
Ranch Hand
Posts: 161
15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If your class has multiple constructors and you have initialization code that must run in every constructor, instead of manually duplicating the code in every constructor or repeatedly calling this(), you can use an instance initializer.
 
Paul Clapham
Sheriff
Posts: 21107
32
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Or if you have an anonymous inner class, which can't have a constructor, then you might need an instance initializer. .
 
Sachin Tripathi
Ranch Hand
Posts: 368
3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Consider this if you have certain block of code that you want to execute every time whenever instance of that particular class is created,and you have many constructors
You can try following:
1-Put the code separetly in all constructors
2-Put it into a method or any constructor then you can invoke them in every other constructor
3-Put it into instance initializer,all the codes get placed in the constructor automatically,which creates the instance of class
 
Joe Bishara
Ranch Hand
Posts: 161
15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sachin Tripathi wrote:1-Put the code separetly in all constructors

I don’t agree with this because of DRY (don’t repeat yourself). Code duplication can cause maintenance problems.

Sachin Tripathi wrote:2-Put it into a method...

I agree with this but the method must be final because according to Bloch, calling overridable methods during instance initialization can cause problems.
 
Sachin Tripathi
Ranch Hand
Posts: 368
3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello Joe,I was telling op all the possible ways of doing that,not just the optimal one
And it was all left to op to determine which is the most suitable one,so that he can understand the use of instance initializer perfectly
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic