Initializing fields in interfaces
Fields defined in interfaces are automatically static and final. These cannot be “blank finals,” but they can be initialized with nonconstant expressions. For example:
//: c08:RandVals.java
// Initializing interface fields with
// non-constant initializers.
import java.util.*;
public interface RandVals {
Random rand = new Random();
int randomInt = rand.nextInt(10);
long randomLong = rand.nextLong() * 10;
float randomFloat = rand.nextLong() * 10;
double randomDouble = rand.nextDouble() * 10;
} ///:~
Since the fields are static, they are initialized when the class is first loaded, which happens when any of the fields are accessed for the first time. Here’s a simple test:
//: c08:TestRandVals.java
import com.bruceeckel.simpletest.*;
public class TestRandVals {
private static Test monitor = new Test();
public static void main(String[] args) {
System.out.println(RandVals.randomInt);
System.out.println(RandVals.randomLong);
System.out.println(RandVals.randomFloat);
System.out.println(RandVals.randomDouble);
monitor.expect(new String[] {
"%% -?\\d+",
"%% -?\\d+",
"%% -?\\d\\.\\d+E?-?\\d+",
"%% -?\\d\\.\\d+E?-?\\d+"
});
}
} ///:~
The fields, of course, are not part of the interface but instead are stored in the static storage area for that interface.