Java Reference
In-Depth Information
Listing 2-18 's Graphics class uses an instance initializer to create an object's
sines and cosines arrays, and to initialize these arrays' elements to the sines and
cosines of angles ranging from 0 through 359 degrees. It does so because it's faster
to read array elements than to repeatedly call Math.sin() and Math.cos() else-
where;performancematters.( Chapter4 introduces Math.sin() and Math.cos() .)
A class can declare a mix of instance initializers and instance field initializers, as
shown in Listing 2-19 .
Listing 2-19. Mixing instance initializers with instance field initializers
class C
System.out.println("instance initializer 1");
int counter = 1;
System.out.println("instance initializer 2");
System.out.println("counter = "+counter);
Listing2-19 declaresaclassnamed C thatspecifiestwoinstanceinitializersandone
instance field initializer. When the Java compiler compiles a class into a classfile, it
createsaspecial void <init>() methodrepresentingthedefaultnoargumentcon-
structor when no constructor is explicitly declared; otherwise, it create an <init>()
they occur (from top to bottom).
Note <init> isnotavalidJavamethodname,butisavalidnamefromtheruntime
flict with any init() methods that you might declare in the class.
For class C , <init>() would first contain the bytecode equivalent of Sys-
tem.out.println("instance initializer 1"); , it would next contain
Search WWH ::

Custom Search