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;
Listing2-38 presentsaclasshierarchyconsistingofasuperclassnamed A andasub-
class named B . Although A does not declare any members, B declares a single m()
Athirdclassnamed DowncastDemo providesa main() methodthatfirstinstanti-
ates A ,andthentriestodowncastthisinstanceto B andassigntheresulttovariable b .
the same type hierarchy is legal.
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.
legal.Becauseitdetectsthat A doesnothavean m() method,itdoesnotpermitthecast
by throwing an instance of the ClassCastException class.
Search WWH ::

Custom Search