Unusual members, part 1
by , 08-12-2011 at 12:09 AM (639 Views)
Did you ever want to run something the first, and only first, time a class was being used.
Perhaps wanted to do some complex calculations and assign it to a constant.
One way to do this is by writing, for example:
All static variables are assigned direct when the class is first being used,Java Code:public class YourClass { public static final int YOUR_CONSTANT = constantValue(); private static int constantValue() { int value1 = 0, value2 = 1; int value = 0; for (int i = 0; i < 10; i++) { value = value1 + value2; value2 = value1; value1 = value; } return value: } }
so if you want to print "Hello", you could do so in a method used by a dummy variable.
But there is a much prettier way to do this, especially for more complex code: by using a class initialiser:Java Code:public class YourClass { private static final Void IM_A_DUMMY = printHello(); private static Void printHello() { System.out.println("Hello"); return null; } }
Running main() will print:Java Code:public class MyClass { private static final Void DUMMY = dummysCode(); public static final int VALUE; /** * Class initialiser */ static { System.out.println("Hello"); VALUE = 10; } private static final Void ANOTHER_DUMMY = anotherDummysCode(); static { System.out.println("Initialised!"); } private static Void dummysCode() { System.out.println("Dummy's code"); return null; } private static Void anotherDummysCode() { System.out.println("Another dummy's code"); return null; } public static void main(final String... arg) { System.out.println(VALUE); } }
Dummy's code
Hello
Another dummy's code
Initialised!
10
Variable as assigned from the top down, running any class initialiser in the way.









Email Blog Entry
sorry for all the questions
thanks...
06-14-2013, 02:22 PM in gbonecapone