Java Reference
In-Depth Information
station = x;
}
static {
System.out.println(“Inside static initializer”);
}
}
The following StaticInitDemo program instantiates a Radio object. Study the
program and try to determine the output. Pay particular attention to when the
static initializer executes. The output is shown in Figure 7.7.
public class StaticInitDemo
{
public static void main(String [] args)
{
System.out.println(“Inside main”);
Radio r1 = new Radio(1380);
Radio r2 = new Radio(850);
}
}
The only purpose I have seen for static initializers occurs when a Java
program is using the Java Native Interface (JNI) to invoke a native function
(typically written in C or C++). For the Java program to be able to invoke a
native function, the function needs to appear in a function library, which
needs to be loaded exactly once.
We will not be discussing JNI, nor will we ever have a reason to use static
initializers in this topic. I just wanted you to be aware that static initializers
exist, in case you run into one someday or find a need to use one in a
class.
Figure 7.7
The output of the StaticInitDemo program.
Search WWH ::




Custom Search