Static Initialization blocks :: This is also referred as “static blocks” or “static initializer”.Static blocks are bundle of valid Java statements within {curly braces} prefixed with static keyword.
syntax: static { //your code goes here}
Static blocks are executed, at the time of class loading.Executed only once, at the time class loading.
Static blocks can be used to initialize static data members and invoke static methods only.
Since static blocks are belongs to class, this and super keywords are not allowed.
Order of execution: Static blocks are always executed first comparing with instance blocks, at the time class loading.
package utlfunc;
public class GraspStatc {
public GraspStatc() {
System.out.println("from GraspStatc constructor ");
}
static {
System.out.println("from static blcok1");
}
{
System.out.println("from initialization block1");
}
static {
System.out.println("from static blcok2");
}
{
System.out.println("from initialization block2");
}
public static void main(String[] args) {
GraspStatc gs=new GraspStatc();
}
}
order of execution of blocks in class: 1)while classloading static block will execute first.
2) Second initialization block will execute.
3)constructor will execute.
Output:
Inheritance hierarchy::
SubClass as above example.Super class below
package utlfunc;
public class SubStatcInit {
public SubStatcInit() {
System.out.println(" From SubStatcInit() constructor");
}
static {
System.out.println("from static blcok1 from SubStatcInit");
}
{
System.out.println("from initialization block1 from SubStatcInit");
}
static {
System.out.println("from static blcok2 from SubStatcInit");
}
{
System.out.println("from initialization block2 from SubStatcInit");
}
}
Output::
No comments:
Post a Comment