Java Reference
In-Depth Information
Why Use an Instance Initializer?
You can write lots of Java classes that do not use instance initializers. A constructor can
always be used to initialize any fi elds of an object. Some developers like to use instance
initializers for code readability, because you can put an instance initializer in the vicinity
of your fi eld declarations. For example, the following Button objects in the ColorChanger
class do not rely on constructor arguments to be initialized:
7. public class ColorChanger extends Frame {
8. private Button redBtn, whiteBtn, blueBtn;
9. {
10. redBtn = new Button(“Red”);
11. whiteBtn = new Button(“White”);
12. blueBtn = new Button(“Blue”);
13. }
In this scenario, it really does not matter if the Button objects are instantiated in a
constructor or an instance initializer, so using an instance initializer might make the code
more readable, especially if this is a large source fi le with multiple constructors.
Static Initializers
A static initializer is a block of code that executes once when a class is loaded by the class
loader. The syntax for a static initializer is the static keyword followed by a set of curly
braces:
static {
//a static initializer
}
A class can contain multiple static initializers. They are executed in the order they
appear in the source fi le. The purpose of a static initializer is to perform any complex
initialization of static fi elds in the class or to perform any tasks that need to be performed
only once. For example, a common use of static initializers is to load system libraries:
1. public class MyLibrary {
2. static {
3. System.loadLibrary(“mylibrary”);
4. }
5.
6. //remainder of class definition
7. }
Search WWH ::




Custom Search