Java Reference
In-Depth Information
Note <clinit> is not a valid Java method name, but is a valid name from the
runtimeperspective. Theanglebracketswerechosenaspartofthenametopreventa
name conflict with any clinit() methods that you might declare in the class.
For class C , <clinit>() would first contain the bytecode equivalent of Sys-
tem.out.println("class initializer 1"); , it would next contain the
bytecode equivalent of static int counter = 1; , and it would finally
contain the bytecode equivalent of System.out.println("class initial-
izer 2"); System.out.println("counter = "+counter); .
Whenclass C isloadedintomemory, <clinit>() executesimmediatelyandgen-
erates the following output:
class initializer 1
class initializer 2
counter = 1
Instance Initializers
Notallclassescanhaveconstructors,asyouwilldiscoverin Chapter3 whenIpresent
anonymousclasses.Fortheseclasses,Javasuppliestheinstanceinitializertotakecare
of instance initialization tasks.
An instance initializer isablockthatisintroducedintoaclassbody,asopposedtobe-
ingintroducedasthebodyofamethodoraconstructor.Theinstanceinitializerisused
to initialize an object via a sequence of statements, as demonstrated in Listing 2-18 .
Listing 2-18. Initializing a pair of arrays via an instance initializer
class Graphics
{
double[] sines;
double[] cosines;
{
sines = new double[360];
cosines = new double[sines.length];
for (int i = 0; i < sines.length; i++)
{
sines[i] = Math.sin(Math.toRadians(i));
cosines[i] = Math.cos(Math.toRadians(i));
}
 
Search WWH ::




Custom Search