Java Reference
In-Depth Information
In main() , you generate an object of type TryInitialization and then call its listValues() method.
You 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.
Because the values array is a static member of the class, you could list the element's values through
a static method that would not require any objects to have been created. Try temporarily adding the
keyword static to the declaration of the listValues() method in the class:
static void listValues() {
System.out.println(); // Start a new line
for(int value : values) {
System.out.print(" " + value); // Display values
}
System.out.println(); // Start a new line
}
You can now call the method using the class name, so add two extra statements at the beginning of
main() :
System.out.println("\nNo object:");
TryInitialization.listValues();
If you compile and execute the program with these changes, you get an additional record of the values
in the values array. You still get the output from calling listValues() using the two object references.
Every object has access to the static members of its class. Of course, the values in the output are different
from the previous execution because they are pseudo-random values.
If you restore the program to its original state, and then delete the static modifier before the initializa-
tion block and recompile and run the program again, you get the output along the lines of the following:
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 you 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();
Search WWH ::




Custom Search