Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

static, instance, constructor call order

 
Sweta Pillai
Greenhorn
Posts: 28
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The following code



when evaluated produces the o/p as follows:
A's static
B's static
A's Instance
A's Constructor
B's Instance
B's Constructor
Why after A's static, the flow comes to B's static, why not complete the
A's instance and constructor call ???
 
chintan ramavat
Ranch Hand
Posts: 134
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi..

look at following one , it might clear your doubt

class C {

static int j = 12;
static { System.out.println(j);}

C() { System.out.println("in C");
}}


class B {

static int i = 10;
static {i++; System.out.println(i);}

// STATIC VARIABLES / STATIC initializer executes first
C c = new C();


}


class SUPRE extends B{

public static void main(String []args){
new SUPRE();
}}


so -- 1st static var, 2 static init-block 3 rest body of the class
 
Manfred Klug
Ranch Hand
Posts: 377
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Sweta Pillai:
Why after A's static, the flow comes to B's static, why not complete the
A's instance and constructor call ???
Since first the needed classes are loaded and initialized. And after the initialization, the new instance is created.

A's static => Load and initialize of class A
B's static => Load and initialize of class B

The initialization of the B instance starts here. And these four parts are repeated every time you construct a new B.
A's Instance
A's Constructor
B's Instance
B's Constructor
Has as result:

A's static
B's static

A's Instance
A's Constructor
B's Instance
B's Constructor

A's Instance
A's Constructor
B's Instance
B's Constructor
 
Arun Kumar Gaddam
Ranch Hand
Posts: 58
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hai Swetha,

The order of the blocks to execute are,

First static block code is executed when the class is loaded into the JVM.Then comes the Initializing blocks of the first class of the inheritance tree and then the constructor of it,this is because every constructor contains an call to its super constructor(The main point is Initializing blocks run just before the instance is created).This order comes down till the last class and continues with the rest of the code.
 
Sweta Pillai
Greenhorn
Posts: 28
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Manfred,
thanks -that's a pretty cool explanation. I must have tried to instantiate
one more B.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic