Thursday, February 10, 2011

Member Initialization at Definition and Static Constructors

Instance and static variables can be initialized at their point of definition in both C# and Java. If the member variable is an instance variable, then initialization occurs just before the constructor is called. Static members are initialized sometime before the first usage of the member and before the first creation of an instance of the class. It is also possible to specify a block of code that should run before the class is used either via creation of an instance variable or invocation of a static method. These code blocks are called are called static constructors in C# and static initialization blocks in Java. Static constructors are invoked before the first invocation of a static method in the class and before the first time an instance of the class is created.
C# Code
using System;

class StaticInitTest{


string instMember = InitInstance();

string staMember = InitStatic();


StaticInitTest(){
Console.WriteLine("In instance constructor");
}

static StaticInitTest(){
Console.WriteLine("In static constructor");
}


static String InitInstance(){
Console.WriteLine("Initializing instance variable");
return "instance";
}

static String InitStatic(){
Console.WriteLine("Initializing static variable");
return "static";
}


static void DoStuff(){
Console.WriteLine("Invoking static DoStuff() method");
}


public static void Main(string[] args){

Console.WriteLine("Beginning main()");

StaticInitTest.DoStuff();

StaticInitTest sti = new StaticInitTest();

Console.WriteLine("Completed main()");

}

}

Java Code
class StaticInitTest{


String instMember = initInstance();

String staMember = initStatic();


StaticInitTest(){
System.out.println("In instance constructor");
}

static{
System.out.println("In static constructor");
}


static String initInstance(){
System.out.println("Initializing instance variable");
return "instance";
}

static String initStatic(){
System.out.println("Initializing static variable");
return "static";
}


static void doStuff(){
System.out.println("Invoking static DoStuff() method");
}


public static void main(String[] args){

System.out.println("Beginning main()");

StaticInitTest.doStuff();

StaticInitTest sti = new StaticInitTest();

System.out.println("Completed main()");

}

}


OUTPUT FROM BOTH EXAMPLES:
In static constructor
Beginning main()
Invoking static DoStuff() method
Initializing instance variable
Initializing static variable
In instance constructor
Completed main()

No comments:

Post a Comment