Java Reference
In-Depth Information
Each object'sreference isassigned toareference variable named image ,replacing
the previously stored reference for the second and third object assignments. (Each oc-
currenceof System.out.println(); outputsablanklinetomaketheoutputeasi-
er to read.)
The presence of main() changes Image from only a class to an application. You
typically place main() in classes that are used to create objects in order to test
such classes. When constructing an application for use by others, you usually declare
main() inaclasswheretheintentistorunanapplicationandnottocreateanobject
fromthatclass—theapplicationisthenrunfromonlythatclass.See Chapter1 ' s Hel-
loWorld class for an example.
After saving Listing 2-2 to , compile this file by executing javac atthecommandline.Assumingthattherearenoerrormessages,execute
the application by specifying java Image . You should observe the following output:
Image() called
Image(String filename, String imageType) called
reading image.png
Image(String filename) called
Image(String filename, String imageType) called
reading image.png
interpreting image.png as storing a PNG image
sequent output lines indicate that the second and third constructors have been called.
In addition to declaring parameters, a constructor can declare variables within its
body to help it perform various tasks. For example, the previously presented
Image(String filename, String imageType) constructormightcreatean
objectfroma(hypothetical) File classthatprovidesthemeanstoreadafile'scontents.
to a variable, as demonstrated in the following:
Image(String filename, String imageType)
System.out.println("Image(String filename, String im-
ageType) called");
if (filename != null)
Search WWH ::

Custom Search