> Perhaps I have been drawn to the dark side but I really want to have:
But this isn't a C# newsgroup...
> public class Myclass {
>
> private static int myVar = 0;
>
> static Myclass {
That should read:
static {
> mVar = InitializeValue();
> }
> Since one might forget to initialize the class with Myclass myclass =
> new Myclass();
> I would have to check within every static method to see if
> InitializeValue had executed and execute it if not.
Using any static method of class constitutes use of the class, even
without calling an instance constructor. The static initialiser will
therefore have run. If you used an instance initialiser instead of
static initialiser, then the code would run for every instance created.
If you really want to you can get hold of the Class object for a class
without initialisation using Class.forName(String,false,ClassLoader).
Tom Hawtin

Signature
Unemployed English Java programmer
http://jroller.com/page/tackline/
timasmith@hotmail.com - 06 Dec 2005 03:46 GMT
You can do either:
public class Myclass {
private static int myVar = InitializeValue();
public static int getMyVar() {
return myVar;
}
private static void InitializeValue() {
myVar = needToAlwaysInitThisFirst();
}
....
}
or:
public class Myclass {
private static int myVar = 0;
static {
myVar = needToAlwaysInitThisFirst();
}
public static int getMyVar() {
return myVar;
}
....
}
Either way, myVar will be initialized prior to any use of MyClass.
Regards
timasmith@hotmail.com - 06 Dec 2005 03:46 GMT
You could always declare a private constructor and have a static method
for getting an instance of the class.
public class MyClass {
private int myVar = 0;
private MyClass {
myVar = initializeValue();
}
public MyClass getInstance() {
return new MyClass();
}
}
or you could use a static init block if you want the variable to remain
static.
public class MyClass {
private static int myVar = 0;
static {
mVar = initializeValue();
}
public MyClass() {
}
}