Java Reference
In-Depth Information
TheJVM'scastverificationillustrates
runtime type identification
(orRTTI,forshort).
CastverificationperformsRTTIbyexaminingthetypeofthecastoperator'soperandto
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
prevent the
ClassCastException
:
if (a instanceof B)
{
B b = (B) a;
b.m();
}
The
instanceof
operatordetectsthatvariable
a
'sinstancewasnotcreatedfrom
B
andreturnsfalsetoindicatethisfact.Asaresult,thecodethatperformstheillegalcast
will not execute. (Overuse of
instanceof
probably indicates poor software design.)
Becauseasubtypeisakindofsupertype,
instanceof
willreturntruewhenitsleft
operandisasubtypeinstanceorasupertypeinstanceofitsrightoperandsupertype.The
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
.
Youcanalsodowncastfromonearraytoanotherprovidedthatthearraybeingdown-
castisasupertypeoftheotherarray,andwhoseelementstypesarethoseofthesubtype.
Consider
Listing 2-39
.
Listing 2-39.
Demonstrating array downcasting
class Point
{
private int x, y;