Is the following OK?
Object obj; String str = "Yertle" ; obj = str; ((YouthBirthday)obj).greeting();
No.
instanceof
Operator
A typecast is used to tell the compiler what is "really"
in a variable that itself is not specific enough.
You have to tell the truth.
In a complicated program,
a reference variable might end up with any of several
different objects, depending on the input data or other
unpredictable conditions.
To deal with this, the instanceof
operator is used.
variable instanceof Class
This operator evaluates to true
or false
depending on whether the variable refers to an object of
type Class.
For example in the following fragment,
instanceof
is used to ensure that the object
referenced by obj
is used correctly:
Object obj; YouthBirthday ybd = new YouthBirthday( "Ian", 4 ); String str = "Yertle" ; obj = ybd; if ( obj instanceof YouthBirthday ) ((YouthBirthday)obj).greeting(); if ( obj instanceof String ) System.out.print( (String)obj );
instanceof
will also return true
if the
class of the object on the left is a child
(or grandchild or greatgrandchild or ...)
of the class on the right.
If you don't know in advance what classes a variable might hold,
will instanceof
help?