Java Reference
In-Depth Information
Method
Description
toString
This method (introduced in Section 9.4.1) returns a
String
representation of an
object. The default implementation of this method returns the package name and
class name of the object's class typically followed by a hexadecimal representation of
the value returned by the object's
hashCode
method.
wait
,
notify
,
notifyAll
Methods
notify
,
notifyAll
and the three overloaded versions of
wait
are related to
multithreading, which is discussed in Chapter 23.
getClass
Every object in Java knows its own type at execution time. Method
getClass
(used
in Sections 10.5 and 12.5) returns an object of class
Class
(package
java.lang
)
that contains information about the object's type, such as its class name (returned
by
Class
method
getName
).
finalize
This
protected
method is called by the garbage collector to perform termination
housekeeping on an object just before the garbage collector reclaims the object's
memory. Recall from Section 8.10 that it's unclear whether, or when,
finalize
will
be called. For this reason, most programmers should avoid method
finalize
.
clone
This
protected
method, which takes no arguments and returns an
Object
refer-
ence, makes a copy of the object on which it's called. The default implementation
performs a so-called
shallow copy
—instance-variable values in one object are cop-
ied into another object of the same type. For reference types, only the references are
copied. A typical overridden
clone
method's implementation would perform a
deep copy
that creates a new object for each reference-type instance variable.
Imple-
menting
clone
correctly is difficult. For this reason, its use is discouraged.
Some indus-
try experts suggest that object serialization should be used instead. We discuss
object serialization in Chapter 15. Recall from Chapter 7 that arrays are objects. As
a result, like all other objects, arrays inherit the members of class
Object
. Every
array has an overridden
clone
method that copies the array. However, if the array
stores references to objects, the objects are not copied—a shallow copy is per-
formed.
Fig. 9.12
|
Object
methods. (Part 2 of 2.)
Displaying Text and Images Using Labels
Programs often use labels when they need to display information or instructions to the
user in a graphical user interface.
Labels
are a convenient way of identifying GUI compo-
nents on the screen and keeping the user informed about the current state of the program.
In Java, an object of class
JLabel
(from package
javax.swing
) can display text, an image
or both. The example in Fig. 9.13 demonstrates several
JLabel
features, including a plain
text label, an image label and a label with both text and an image.
1
// Fig 9.13: LabelDemo.java
2
// Demonstrates the use of labels.
3
import
java.awt.BorderLayout;
4
import
javax.swing.ImageIcon;
Fig. 9.13
|
JLabel
with text and with images. (Part 1 of 2.)