Java Reference
In-Depth Information
PITFALL: Downcasting
It is the responsibility of the programmer to use downcasting only in situations where
it makes sense. The compiler makes no checks to see if downcasting is reasonable.
However, if you use downcasting in a situation in which it does not make sense, you
will usually get a run-time error message.
■
TIP: Checking to See Whether Downcasting Is Legitimate
★
You can use the
instanceof
operator to test whether or not downcasting is sensible.
Downcasting to a specific type is reasonable if the object being cast is an instance of
that type, which is exactly what the
instanceof
operator tests for.
The
instanceof
operator checks whether an object is of the type given as its second
argument. The syntax is
Object
instanceof
Class_Name
instanceof
which returns
true
if
Object
is of type
Class_Name
; otherwise it returns
false
. So,
the following will return
true
if
someObject
is of type
DiscountSale
:
someObject
instanceof
DiscountSale
Note that because every object of every descendent class of
DiscountSale
is also
of type
DiscountSale
, this expression will return
true
if
someObject
is an instance
of any descendent class of
DiscountSale
.
So, if you want to type cast to
DiscountSale
, then you can make the casts safer
as follows:
DiscountSale ds =
new
DiscountSale();
if
(someObject
instanceof
DiscountSale)
{
ds = (DiscountSale)someObject;
System.out.println("ds was changed to " + someObject);
}
else
System.out.println("ds was not changed.");
someObject
might be, for example, a variable of type
Sale
or of type
Object.
■