Java Reference
In-Depth Information
Although an upcast is always safe (the superclass's interface is a subset of the sub-
class'sinterface),thesamecannotbesaidofadowncast. Listing2-38 showsyouwhat
kind of trouble you can get into when downcasting is used incorrectly.
Listing 2-38. The trouble with downcasting
class A
{
}
class B extends A
{
void m() {}
}
class DowncastDemo
{
public static void main(String[] args)
{
A a = new A();
B b = (B) a;
b.m();
}
}
Listing2-38 presentsaclasshierarchyconsistingofasuperclassnamed A andasub-
class named B . Although A does not declare any members, B declares a single m()
method.
Athirdclassnamed DowncastDemo providesa main() methodthatfirstinstanti-
ates A ,andthentriestodowncastthisinstanceto B andassigntheresulttovariable b .
Thecompilerwillnotcomplainbecausedowncastingfromasuperclasstoasubclassin
the same type hierarchy is legal.
However,iftheassignmentisallowed,theapplicationwillundoubtedlycrashwhen
it tries toexecute b.m(); .The crash happens because the JVMwill attempt tocall a
method that does not exist—class A does not have an m() method.
Fortunately,thisscenariowillneverhappenbecausetheJVMverifiesthatthecastis
legal.Becauseitdetectsthat A doesnothavean m() method,itdoesnotpermitthecast
by throwing an instance of the ClassCastException class.
 
Search WWH ::




Custom Search