Java Reference
In-Depth Information
Althoughitappearsotherwise,constructorsdon'thavenames(althoughitiscommon
torefertoaconstructorbyspecifyingtheclassnameandparameterlist).Aconstructor
calls another constructor by using keyword
this
and a round bracket-delimited and
comma-separated list of arguments. For example,
Image(String filename)
executes
this(filename, null);
to execute
Image(String filename,
String imageType)
.
Caution
Youmustuse
this
tocallanotherconstructor—youcannotusetheclass's
name,asin
Image()
.The
this()
constructorcall(ifpresent)mustbethefirstcode
thatisexecutedwithintheconstructor.Thisrulepreventsyoufromspecifyingmultiple
this(
)constructorcallsinthesameconstructor.Finally,youcannotspecify
this()
in a method—constructors can be called only by other constructors and during object
creation. (I will discuss methods later in this chapter.)
When present, the constructor call must be the first code that is specified within
a constructor; otherwise, the compiler reports an error. For this reason, a constructor
that calls another constructor can only perform additional work after the other con-
structor has finished. For example,
Image(String filename)
executes
Sys-
tem.out.println("Image(String filename) called");
after the in-
voked
Image(String filename, String imageType)
constructor finishes.
The
Image(String filename, String imageType)
constructordeclares
an
imageType
parameterthatsignifiesthekindofimagestoredinthefile—aPortable
Network Graphics (PNG) image, for example. Presumably, the constructor uses
im-
ageType
tospeedupprocessingbynotexaminingthefile'scontentstolearntheimage
format.When
null
ispassedto
imageType
,ashappenswiththe
Image(String
filename)
constructor,
Image(String filename, String imageType)
examines file contents to learn the format. If
null
was also passed to
filename
,
Image(String filename, String imageType)
wouldn'treadthefile,but
would presumably notify the code attempting to create the
Image
object of an error
condition.
create
Image
objectsandviewoutputmessages.
main()
createsthree
Image
objects,
calling the first constructor with no arguments, the second constructor with argument
"image.png"
,andthethirdconstructorwitharguments
"image.png"
and
"PNG"
.
Note
Thenumberofargumentspassedtoaconstructorormethod,orthenumberof
operator operands is known as the constructor's, method's, or operator's
arity
.