Java Reference
In-Depth Information
Speaker
and overrides its
speak()
method. When this method is called, it outputs
main()
'sfirstcommand-lineargumentoradefaultmessageiftherearenoarguments;
for example,
java ACDemo Hello
outputs
Hello
.
Ananonymousclassdoesnothaveaconstructor(becausetheanonymousclassdoes
not have a name). However, its classfile does contain an
<init>()
method that per-
formsinstanceinitialization.Thismethodcallsthesuperclass'snoargumentconstructor
(priortoanyotherinitialization),whichisthereasonforspecifying
Speaker()
after
new
.
Anonymous class instances should be able to access the surrounding scope's local
variables and parameters. However, an instance might outlive the method in which it
wasconceived(asaresultofstoringtheinstance'sreferenceinafield),andtrytoaccess
local variables and parameters that no longer exist after the method returns.
BecauseJavacannotallowthisillegalaccess,whichwouldmostlikelycrashtheJava
VirtualMachine(JVM),itletsananonymousclassinstanceonlyaccesslocalvariables
andparametersthataredeclared
final
.Uponencounteringafinallocalvariable/para-
meter name in an anonymous class instance, the compiler does one of two things:
• Ifthevariable'stypeisprimitive(
int
or
double
,forexample),thecompiler
replaces its name with the variable's read-only value.
• If the variable's type is reference (
java.lang.String
, for example), the
compiler introduces, into the classfile, a
synthetic variable
(a manufactured
variable) and code that stores the local variable's/parameter's reference in the
synthetic variable.
Listing 3-11
demonstrates an alternative anonymous class declaration and instanti-
ation.
Listing 3-11.
Declaring and instantiating an anonymous class that implements an interface
interface Speakable
{
void speak();
}
class ACDemo
{
public static void main(final String[] args)
{
new Speakable()
{