Java Reference
In-Depth Information
double yCenter = 10.0; // of the center
double zCenter = 10.0; // of a sphere
// Rest of the class...
}
Now every object of type Sphere starts out with a radius of 5.0 and has the center at the point (10.0, 10.0,
10.0).
Some things can't be initialized with a single expression. For example, if you have a large array as a data
member that you want to initialize, with a range of values that required some kind of calculation, this could
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 is executed once
when the class is loaded. A static initialization block can initialize only 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 a working example.
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 value : values) {
System.out.print(" " + value);
// Display values
Search WWH ::




Custom Search