WebReference.com - Part 1 of chapter 5 from Beginning Java 2 SDK 1.4 Edition, Wrox Press Ltd (8/8)
[previous] |
Beginning Java 2 SDK 1.4 Edition
Initializing Data Members
We have seen how we were able to supply an initial value for the static members PI
and
count
in the Sphere
class with the declaration:
class Sphere {
static final double PI = 3.14; // Class variable that has a fixed value
static int count = 0; // Class variable to count objects
// Rest of the class...
}
We can also initialize ordinary non-static data members in the same way. For example:
class Sphere {
static final double PI = 3.14; // Class variable that has a fixed value
static int count = 0; // Class variable to count objects
// Instance variables
double radius = 5.0; // Radius of a sphere
double xCenter = 10.0; // 3D coordinates
double yCenter = 10.0; // of the center
double zCenter = 10.0; // of a sphere
// Rest of the class...
}
Now every object of type Sphere
will start out with a radius
of
5.0
and have the center at the point 10.0, 10.0, 10.0
.
There are some things that can't be initialized with a single expression. If you had a large array as a data member for example, that you wanted to initialize, with a range of values that required some kind of calculation, this would be a job for an initialization block.
Using Initialization Blocks
An initialization block is a block of code between braces that is executed before an object
of the class is created. There are two kinds of initialization blocks. A static initialization block
is a block defined using the keyword, static
, and that is executed once when the class
is loaded and can only initialize static data members of the class. A non-static initialization block
is executed for each object that is created and thus can initialize instance variables in a class. This
is easiest to understand by considering specific code.
Try It Out--Using an Initialization Block
Let's define a simple class with a static initialization block first of all:
class TryInitialization {
static int[] values = new int[10]; // Static array member
// Initialization block
static {
System.out.println("Running initialization block.");
for(int i=0; i<values.length; i++)
values[i] = (int)(100.0*Math.random());
}
// List values in the array for an object
void listValues() {
System.out.println(); // Start a new line
for(int i=0; i<values.length; i++)
System.out.print(" " + values[i]); // Display values
System.out.println(); // Start a new line
}
public static void main(String[] args) {
TryInitialization example = new TryInitialization();
System.out.println("\nFirst object:");
example.listValues();
example = new TryInitialization();
System.out.println("\nSecond object:");
example.listValues();
}
}
When you compile and run this you will get identical sets of values for the two objects--as might
be expected since the values
array is static:
Running initialization block.
First object:
40 97 88 63 58 48 84 5 32 67
Second object:
40 97 88 63 58 48 84 5 32 67
How it Works
The TryInitialization
class has a static member, values
, that is an array
of 10 integers. The static initialization block is the code:
static {
System.out.println("Running initialization block.");
for(int i=0; i<values.length; i++)
values[i] = (int)(100.0*Math.random());
}
This initializes the values
array with pseudo-random integer values generated in the
for
loop. The output statement in the block is there just to record when the initialization
block executes. Because this initialization block is static, it is only ever executed once during program execution, when the class is loaded.
The listValues()
method provides us with a means of outputting the values in the array.
The print()
method we are using in the listValues()
method works just like
println()
, but without starting a new line before displaying the output, so we get all
the values on the same line.
In main()
, we generate an object of type TryInitialization
, and then call its
listValues()
method. We then create a second object and call the listValues()
method for that. The output demonstrates that the initialization block only executes once, and that
the values reported for both objects are the same.
If you delete the modifier static
from before the initialization block, and recompile
and run the program again, you will get the output along the lines of:
Running initialization block.
First object:
66 17 98 59 99 18 40 96 40 21
Running initialization block.
Second object:
57 86 79 31 75 99 51 5 31 44
Now we have a non-static initialization block. You can see from the output that the values are
different for the second object because the non-static initialization block is executed each time an
object is created. In fact, the values
array is static, so the array is shared between
all objects of the class. You could demonstrate this by amending main()
to store each
object separately, and calling listValues()
for the first object after the second object
has been created. Amend the main()
method in the program to read as follows:
public static void main(String[] args) {
TryInitialization example = new TryInitialization();
System.out.println("\nFirst object:");
example.listValues();
TryInitialization nextexample = new TryInitialization();
System.out.println("\nSecond object:");
nextexample.listValues();
example.listValues();
}
While we have demonstrated that this is possible, you will not normally want to initialize static variables with a non-static initialization block.
As we said at the outset, a non-static initialization block can initialize instance variables too. If
you want to demonstrate this too, you just need to remove the static
modifier from the
declaration of values
and compile and run the program once more.
You can have multiple initialization blocks in a class, in which case they execute in the sequence in which they appear. The static blocks execute when the class is loaded and the non-static blocks execute when each object is created. Initialization blocks are useful, but you need more than that to create objects properly. [To be continued... -Ed.]
[previous] |
Created: June 24, 2002
Revised: June 24, 2002
URL: https://webreference.com/programming/java/beginning/chap5/1/8.html