• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • paul wheaton
  • Liutauras Vilda
  • Ron McLeod
Sheriffs:
  • Jeanne Boyarsky
  • Devaka Cooray
  • Paul Clapham
Saloon Keepers:
  • Scott Selikoff
  • Tim Holloway
  • Piet Souris
  • Mikalai Zaikin
  • Frits Walraven
Bartenders:
  • Stephan van Hulst
  • Carey Brown

static blocks

 
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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?
 
Bartender
Posts: 10780
71
Hibernate Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
reply
    Bookmark Topic Watch Topic
  • New Topic