Java Reference
In-Depth Information
Exercise 5.3. Add static initializers to j--, adding it to your compiler and testing it thor-
oughly.
A static initializer is a class (or interface) member. It is a block of initializing code that
is executed before the class enclosing it is referenced. It is identified by the static keyword
as in
static{
...
}
The code in the static initializer is executed before the enclosing class is referenced. As such,
the code goes into the <clinit> method the same place that class field initializations go.
To learn more about static initializers, see Section 8.7 of the Java Language Specification
[Gosling et al., 2005]. The order that fields and static initializers are executed (and so the
order they appear in <clinit> ) is the order that the members appear in the class; the only
exception to this is \that final class variables and fields of interfaces whose values are
compile-time constants are initialized rst." See Section 12.4.2 of [Gosling et al., 2005].
Rules that static initializers must follow include
1. It is a compile-time error to throw an exception or to return in the initializing code.
2. Static initializers may not refer to this or super .
3. There are restrictions in referring to class variables that are defined textually further
in the code.
Exercise 5.4. Add instance initializers to j--, adding it to your compiler and testing it
thoroughly.
An instance initializer is a block of initializing code that is executed each time an
instance of the enclosing class is instantiated. Therefore, its code goes into the constructors,
that is <init> . Make sure this code is not executed twice, that is, in a constructor whose
code starts off with this() .
Rules that instance initializers must follow include
1. It is a compile-time error to throw an exception or to return in the initializing code.
2. Instance initializers may refer to this .
Exercise 5.5. Java permits the declaration of methods of variable arity. For example, one
might declare a method
publicvoidfoo(intx,Stringy,int...z){<body>}
Invocations of foo require an int value for x , a String value for y , and then any number
(including zero) of int s, all of which are gathered into an implicitly declared integer array
z . Implementing variable arity methods requires declaring the implicit array at method
declaration time, and then gathering the (extra) actual arguments into an array at method
invocation time. Add variable arity methods to j--, adding them to your compiler and testing
them thoroughly.
Exercise 5.6. Add the do-while statement to j--, adding it to your compiler and testing it
thoroughly.
The do-while statement takes the form
do{
Statement
}
while(Test);
 
Search WWH ::




Custom Search