Java Reference
In-Depth Information
casting must be used to confirm your intention to the compiler with the
(SubclassName)
cast notation. For the casting to be successful, you must make sure that the object to be cast is
an instance of the subclass. If the superclass object is not an instance of the subclass, a runtime
ClassCastException
occurs. For example, if an object is not an instance of
Student
, it
cannot be cast into a variable of
Student
. It is a good practice, therefore, to ensure that the
object is an instance of another object before attempting a casting. This can be accomplished
by using the
instanceof
operator. Consider the following code:
ClassCastException
instanceof
Object myObject =
new
Circle();
...
// Some lines of code
/** Perform casting if myObject is an instance of Circle */
if
(myObject
instanceof
Circle) {
System.out.println(
"The circle diameter is "
+
((Circle)myObject).getDiameter());
...
}
You may be wondering why casting is necessary. The variable
myObject
is declared
Object
. The
declared type
decides which method to match at compile time. Using
myObject.getDiameter()
would cause a compile error, because the
Object
class does not have the
getDiameter
method. The compiler cannot find a match for
myObject.getDiameter()
. Therefore, it is necessary to cast
myObject
into the
Circle
type to tell the compiler that
myObject
is also an instance of
Circle
.
Why not define
myObject
as a
Circle
type in the first place? To enable generic program-
ming, it is a good practice to define a variable with a supertype, which can accept an object
of any subtype.
Note
instanceof
is a Java keyword. Every letter in a Java keyword is in lowercase.
lowercase keywords
Tip
To help understand casting, you may also consider the analogy of fruit, apple, and
orange, with the
Fruit
class as the superclass for
Apple
and
Orange
. An apple is
a fruit, so you can always safely assign an instance of
Apple
to a variable for
Fruit
.
However, a fruit is not necessarily an apple, so you have to use explicit casting to assign
an instance of
Fruit
to a variable of
Apple
.
casting analogy
ListingĀ 11.7 demonstrates polymorphism and casting. The program creates two objects
(lines 5-6), a circle and a rectangle, and invokes the
displayObject
method to display them
(lines 9-10). The
displayObject
method displays the area and diameter if the object is a
circle (line 15), and the area if the object is a rectangle (lines 21-22).
L
ISTING
11.7
CastingDemo.java
1
public class
CastingDemo {
2
/** Main method */
3
public static void
main(String[] args) {
4
// Create and initialize two objects
5 Object object1 =
new
CircleFromSimpleGeometricObject(
1
);
6 Object object2 =
new
RectangleFromSimpleGeometricObject(
1
,
1
);
7
8
// Display circle and rectangle
9
displayObject(object1);
10
displayObject(object2);
11 }
12
Search WWH ::
Custom Search