Java Reference
In-Depth Information
System.out.println("reading "+filename);
File
file
= new File(filename);
// Read file contents into object.
if (imageType != null)
System.out.println("interpreting "+filename+" as
storing a "+
imageType+" image");
else
// Inspect image contents to learn image type.
; // Empty statement is used to make if-else syn-
tactically valid.
}
// Perform other initialization here.
}
Aswiththe
filename
and
imageType
parameters,
file
isavariablethatislocal
to the constructor, and is known as a
local variable
to distinguish it from a parameter.
Although all three variables are local to the constructor, there are two key differences
between parameters and local variables:
• The
filename
and
imageType
parameterscomeintoexistenceatthepoint
wheretheconstructorbeginstoexecuteandexistuntilexecutionleavesthecon-
structor.Incontrast,
file
comesintoexistenceatitspointofdeclarationand
continuestoexistuntiltheblockinwhichitisdeclaredisterminated(viaaclos-
ingbracecharacter).Thispropertyofaparameteroralocalvariableisknown
as
lifetime
.
• The
filename
and
imageType
parameterscanbeaccessedfromanywhere
intheconstructor.Incontrast,
file
canbeaccessedonlyfromitspointofde-
claration to the end of the block in which it is declared. It cannot be accessed
beforeitsdeclarationorafteritsdeclaringblock,butnestedsubblockscanac-
cessthelocalvariable.Thispropertyofaparameteroralocalvariableisknown
as
scope
.
Note
The lifetime and scope (also known as visibility) properties also apply to
classes,objects,andfields(discussedlater).Classescomeintoexistencewhenloaded
into memory and cease to exist when unloaded from memory, typically when an ap-
plicationexits.Also,loadedclassesaretypicallyvisibletootherclasses,butthisisn't
alwaysthecase—AppendixCwillhavemoretosayaboutthisissuewhenitpresents
classloaders.