• Post Reply Bookmark Topic Watch Topic
  • New Topic

static blocks  RSS feed

 
Puneet Hattalli
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

public class B {

static{
System.out.println("super static");
}
public B() {
System.out.println("super constructor");
}
}




public class Test extends B{

static int value;
static {
value = (int)(Math.random()*40);
System.out.println("static with value "+value);
}

public Test() {
System.out.println("constructor");
}

public static void main(String[] args) {
Test t = new Test();

}
}

In above piece of code, why is it that the static block in super class executes first?
Why not the static block from the class containing main?
 
Winston Gutkowski
Bartender
Posts: 10575
66
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Puneet Hattalli wrote:In above piece of code, why is it that the static block in super class executes first?

Because it's loaded first. Certainly the class loader or the JVM sorts that sort of stuff out.

Is there any specific reason you feel you need to know this? It's very obscure.

Winston
 
Sachin H. Gupta
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Following code might help

Output:
Static block of C
Static block of A
Static block of B
Non-static block of A
Constructor of A
Non-static block of B
Constructor of B
 
Puneet Hattalli
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks For the Reply.
Actually i was learning inheritance topic.
I was confused because I thought since main method is the entry point of execution, it would execute code from the static block of main()
method in Test class.
So thanks again for the reply, now I know that since Test Class extends B Class the static blocks of B class are executed first.
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!