Pages

SPONSORED

Static Blocks or Static Constructors

As the name suggests static blocks are used to initialise the static fields of the class.

·         These blocks or methods get executed only once for a class.
·         They are executed even before the constructors are executed.
·         The static fields with initializes in declaration will get executed before the  static blocks.
·         They are triggered when any of the following events occur:
o   An instance of the class is created.
o   If any of the static members of the class is accessed.


 The implementation of this is slightly different in Java and C#.

In Java
All blocks that are declared static are executed when a class is loaded. Static blocks in Java do not have a function name.

public class StaticBlockExample {
public static final int abc = 20;
public static final int def;

//Static block to initialise the static variable def
static {
          if(abc == 20)
def = 10;
else
def = 15;
}
//Constructor gets executed after static block is executed
public StaticBlockExample (){}
}


In C#
Static blocks are called as Static Constructors in C#. They are declared using static constructor declarations.

public class StaticBlockExample
{
static int abc = 20;
static int def;

  static StaticBlockExample ()
  {
if(abc == 20)
def = 10;
else
def = 15;
   }
}

No comments:

Post a Comment