The initialization of static Read-Only variables in Java can be seen in almost all programming languages. All script languages such as Bash and KSh have read-only variables.
We can use static Read-Only variables to store the known and static resources and information during the program running.
In Java, the initialization of read-only variables is flexible. We can use the traditional initialization method, followed by the value after the declaration. For example:
Public Class {
Public static final string resource_a = "aaa.png ";
......
}
In addition, for Array variables, we can use braces to enclose all values to be initialized:
......
Public static final string [] resources = {"aaa.png", "bbb.png", "aaa.txt "};
......
Initialization of other types of data, such as list, map, and other class objects, is not done simply by using the equal sign "=.
In Java, we can use static {...} in the class to initialize static members in the class. The code above will be executed first. Therefore, you can initialize static Read-Only variables in static:
......
Public static final string res_a = "aaa.png ";
Public static final string res_ B = "bbb.png ";
......
Public static final map <string, string> res_map = newhashmap <string, string> ();
......
Static {
Res_map.put ("res_a", res_a );
Res_map.put ("res_ B", res_ B );
......
}
......
For non-static Read-Only variables (static variables are not used, only variables declared by final are used ...... The initialization can be executed directly in the class constructor. In this way, before the class object is born, this read-only variable is unknown, but once the object is generated, its value cannot be changed.
Because the "read-only" variable in Java seems to be variable. the net designer distinguishes the real "read-only" from the "read-only" in Java, which is referred to by the const and readonly keywords respectively.
Below, I will give a very simple example that can be run directly to illustrate the initialization of read-only variables in Java:
Public class Hello {
Public static final string class_final;
Public final string obj_final;
Public Hello (){
Obj_final = "non-static final string .";
}
Static {
Class_final = "static string for class .";
}
Public static void main (string [] ARGs ){
Hello H = new Hello ();
System. Out. println ("Hello! "+ H. obj_final );
System. Out. println ("Hello! "+ Class_final );
}
} Transferred from
Http://blog.csdn.net/eilent/article/details/6928869