Java Reference
In-Depth Information
that is assignment compatible with the type name on its right, and
false
otherwise. Because
null
is not an instance of any type
instanceof
for
null
always returns
false
. Using
instanceof
you can safely downcast a refer-
ence, knowing that no exception will be thrown. For example:
if (sref instanceof More)
mref = (More) sref;
Note that we still have to apply the castthat's to convince the compiler
that we really meant to use the object as a subclass instance.
Type testing with
instanceof
is particularly useful when a method doesn't
require an object of a more extended type but if passed such an object it
can make use of the extended functionality. For example, a
sort
method
may accept a general
List
type as an argument, but if it actually re-
ceives a
SortedList
then it doesn't have to do anything:
public static void sort(List list) {
if (list instanceof SortedList)
return;
// else sort the list ...
}