| Author |
un-named block of code
|
Jitendra Jha
Ranch Hand
Joined: Jan 28, 2007
Posts: 91
|
|
while reading i came across this block of code public class unspec { { System.out.println("Hello"); } unspec() { System.out.println("Hello World"); } public static void main(String args[]) { unspec us=new unspec(); } } this block of code compiles and the unnamed block is executed first,even before constructor. What is this block and what is its purpose. please guide me
|
Jitendra
SCJP1.5
SCWCD1.5
|
 |
Henry Wong
author
Sheriff
Joined: Sep 28, 2004
Posts: 16815
|
|
That "block of code" ... is called an instance initializer. It is executed along with the initialization of your instance variables. In terms of when, it is executed after the super constructor, but before the constructor. Henry
|
Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
|
 |
Jitendra Jha
Ranch Hand
Joined: Jan 28, 2007
Posts: 91
|
|
|
With due respect Henry,it still is not very clear.would you or anyone else please explain it.sorry and thanks for the trouble
|
 |
Henry Wong
author
Sheriff
Joined: Sep 28, 2004
Posts: 16815
|
|
Originally posted by Jitendra Jha: With due respect Henry,it still is not very clear.would you or anyone else please explain it.sorry and thanks for the trouble
With due respect, can you tell us what you are not clear with? We can't read your mind, and just repeating ourselves with different words or examples, is not a very efficient. Henry
|
 |
Ilja Preuss
author
Sheriff
Joined: Jul 11, 2001
Posts: 14112
|
|
Take a look at http://java.sun.com/developer/JDCTechTips/2004/tt0406.html#2 Googling for "instance initializer", it was the first hit.
|
The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
|
 |
Jesper de Jong
Java Cowboy
Bartender
Joined: Aug 16, 2005
Posts: 12953
|
|
Try searching for "java instance initializer" with Google, and you'll find a number of pages that explain what it is. Maybe these are useful: The Essence of OOP using Java, Instance Initializers The Java Tutorial - Initializing Fields (see the bottom of the page) JavaWorld: Object initialization in Java
|
Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
|
 |
 |
|
|
subject: un-named block of code
|
|
|