Java Reference
In-Depth Information
figure 3.10
An example of a
static initializer
1 public class Squares
2 {
3 private static double [ ] squareRoots = new double[ 100 ];
4
5 static
6 {
7 for( int i = 0; i < squareRoots.length; i++ )
8 squareRoots[ i ] = Math.sqrt( ( double ) i );
9 }
10 // Rest of class
11 }
3.6.6 static initializers
Static fields are initialized when the class is loaded. Occasionally, we need a
complex initialization. For instance, suppose we need a static array that stores
the square roots of the first 100 integers. It would be best to have these values
computed automatically. One possibility is to provide a static method and
require the programmer to call it prior to using the array.
An alternative is the static initializer . An example is shown in Figure 3.10.
There, the static initializer extends from lines 5 to 9. The simplest use of the
static initializer places initialization code for the static fields in a block that
is preceded by the keyword static . The static initializer must follow the dec-
laration of the static member.
A static initializer is
a block of code that
is used to initialize
static fields.
example: implementing
a BigRational class
3.7
In this section, we write a class that illustrates many of the concepts that have
been described in this chapter, including
public static final constants
n
n
use of an existing class, namely BigInteger
multiple constructors
n
n
throwing exceptions
implementing a set of accessors
n
n
implementing equals and toString
 
 
Search WWH ::




Custom Search