• Post Reply Bookmark Topic Watch Topic
  • New Topic

Instance Initializer Blocks  RSS feed

 
Patrick Cicero
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Look at the following code

public class InitilizationBlocks
{
public static void main(String[] args)
{
System.out.println("1 IN main"); //1st output
instanceInitilizerClass iIC = new instanceInitilizerClass();
iIC.someMethod();
}

{ System.out.println("2 InitilizationBlock class instance initilizer block"); }


}

class instanceInitilizerClass
{
void someMethod()
{
System.out.println("3 instanceInitilizerClass IN someMethod"); // 4th output

}

// INITIZER block NOT IN {} AND not in a method or constructor
// THIS is called EVEN before the constructor
{ System.out.println("4 IN instanceInitilizer block "); } // 2nd output

instanceInitilizerClass() // Constructor default over-ridden
{
{ System.out.println("5 IN constructor - instanceInitilizer block "); } // 3rd output

}

}

WHEN RUN I GET THE FOLLOWING
1 IN MAIN
4 IN instanceInitilizer block
5 IN constructor - instanceInitilizer block
3 instanceInitilizerClass IN someMethod

IT ALL MAKES SEEMS CORRECT - EXCEPT why when main method of class InitilizationBlocks
THE code System.out.println("2 InitilizationBlock class instance initilizer block"); } NEVER GETS RUN.

I would assume thatwhen that initilization block would run EVEN BEFORE the main method is started.

Is this due to main is static so no instance of that class is ever CREATED --- JUST THE STATIC METHOD main???


 
Paul Clapham
Sheriff
Posts: 22844
43
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Patrick Cicero wrote:

Is this due to main is static so no instance of that class is ever CREATED --- JUST THE STATIC METHOD main???



Yes, exactly. It's called an instance initializer because its purpose is to initialize an instance. So if you don't create any instances, it doesn't get called.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!