• 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
  • Ron McLeod
  • Paul Clapham
  • Devaka Cooray
  • Tim Cooke
Sheriffs:
  • Rob Spoor
  • Liutauras Vilda
  • paul wheaton
Saloon Keepers:
  • Tim Holloway
  • Tim Moores
  • Mikalai Zaikin
  • Carey Brown
  • Piet Souris
Bartenders:
  • Stephan van Hulst

Instance Block vs Constructor

 
Ranch Hand
Posts: 96
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Bartender
Posts: 1849
15
Eclipse IDE Spring VI Editor Java Linux Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Marshal
Posts: 79776
382
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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).
 
Ranch Hand
Posts: 33
1
Android Scala Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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/
 
Java Cowboy
Posts: 16084
88
Android Scala IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
Marshal
Posts: 79776
382
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
Ranch Hand
Posts: 33
1
Android Scala Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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?
 
author
Posts: 23956
142
jQuery Eclipse IDE Firefox Browser VI Editor C++ Chrome Java Linux Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
Marshal
Posts: 79776
382
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Bartender
Posts: 689
17
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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?
 
Saloon Keeper
Posts: 28205
198
Android Eclipse IDE Tomcat Server Redhat Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
Marshal
Posts: 79776
382
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
Marshal
Posts: 79776
382
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Ranch Hand
Posts: 175
17
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Marshal
Posts: 28303
95
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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. .
 
Ranch Hand
Posts: 373
3
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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: 175
17
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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: 373
3
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Let nothing stop you! Not even this tiny ad:
Smokeless wood heat with a rocket mass heater
https://woodheat.net
reply
    Bookmark Topic Watch Topic
  • New Topic