Login | Register   
RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: Java
Expertise: Intermediate
Sep 13, 2000

Static and Object Initializers

Two types of initialization blocks (anonymous blocks) can be used to initialize class or instance variables in Java.

To intialize instance variables,

 {} block
can be used; this block functions similar to a zero-argument constructor. It is useful in anonymous classes where a named constructor cannot be used e.g.
class testInstBlock  {
   private double a;

   a = Math.random();	
To initialize class variables,
block can be used, this block functions similar to a zero argument constructor for class variables. This piece of code is executed when a class is loaded by the JVM. Similar to rules for static methods, the static initializer cannot refer to instance variables--they can refer to static methods and static variables of the class.
class testStaticBlock  {
   private static double a;

static  {
   a = Math.random();	
Mahesh Chulet
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date