This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes why even use initialization blocks at all? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "why even use initialization blocks at all?" Watch "why even use initialization blocks at all?" New topic
Author

why even use initialization blocks at all?

John M. Gabriele
Ranch Hand

Joined: Feb 18, 2001
Posts: 232
can't you always just use constructors and calls to this()?
it seems like init blocks can lead to confusing situations.
Andy Ceponis
Ranch Hand

Joined: Dec 20, 2000
Posts: 782
I think init blocks are used when you have alot of things to initialize at one time. It makes the code clearer to the reader if they can look in one place for all the initialized things instead of having to look through the code to find each individual one.
Manfred Leonhardt
Ranch Hand

Joined: Jan 09, 2001
Posts: 1492
Not with anonymous classes you can't!
Regards,
Manfred.
John M. Gabriele
Ranch Hand

Joined: Feb 18, 2001
Posts: 232
hmm... i could still init a bunch of things right in the first
constructor i write and then put this() (if i wrote them in a
no-arg) calls in the other constructors.
someone perusing the code could see the this() call and then go
back and hunt for the constructor with the same signature as the
this() call to find the initializations...
maybe the init block is used to avoid this kind of "hunting"
(even tho it doesn't seem so bad to me...)?
Randall Twede
Ranch Hand

Joined: Oct 21, 2000
Posts: 4340
    
    2

As Manfred mentioned, annonymous classes cant have constructors and initialization blocks are the only way for them. So they are useful/necessary for that if nothing else.


SCJP
Visit my download page
John M. Gabriele
Ranch Hand

Joined: Feb 18, 2001
Posts: 232
ohh... thanks manfred.
i didn't understand your post and thought maybe you were
responding to andy's comment.
thanks for the heads-up randall.
Andy Ceponis
Ranch Hand

Joined: Dec 20, 2000
Posts: 782
Now im confused. Whats an anonymous class?
Randall Twede
Ranch Hand

Joined: Oct 21, 2000
Posts: 4340
    
    2

here is an example of an annonymous inner class that implements ItemListener interface.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: why even use initialization blocks at all?
 
Similar Threads
Synchronization Issue (Is Runnable the culprit)
Synchronization blocks
help
Transactions and Synchronise blocks
How to Close Connections made In Servlet