Java Reference
In-Depth Information
TheJVM'scastverificationillustrates runtime type identification (orRTTI,forshort).
see whether the cast should be allowed. Clearly, the cast should not be allowed.
A second form of RTTI involves the instanceof operator. This operator checks
the left operand to see whether it is an instance of the right operand, and returns true
ifthisisthecase. Thefollowing example introduces instanceof to Listing 2-38 to
prevent the ClassCastException :
if (a instanceof B)
B b = (B) a;
The instanceof operatordetectsthatvariable a 'sinstancewasnotcreatedfrom B
will not execute. (Overuse of instanceof probably indicates poor software design.)
Becauseasubtypeisakindofsupertype, instanceof willreturntruewhenitsleft
following example demonstrates:
A a = new A();
B b = new B();
System.out.println(b instanceof A); // Output: true
System.out.println(a instanceof A); // Output: true
This example assumes the class structure shown in Listing 2-38 and instantiates su-
perclass A and subclass B . The first System.out.println() method call outputs
true because b 'sreferenceidentifiesaninstanceofasubclassof A ;thesecond Sys-
tem.out.println() methodcalloutputs true because a 'sreferenceidentifiesan
instance of superclass A .
Consider Listing 2-39 .
Listing 2-39. Demonstrating array downcasting
class Point
private int x, y;
Search WWH ::

Custom Search