Is the following OK?
Object obj; String str = "Yertle" ; obj = str; ((YouthBirthday)obj).greeting();
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
To deal with this, the
instanceof operator is used.
variable instanceof Class
This operator evaluates to
depending on whether the variable refers to an object of
For example in the following fragment,
instanceof is used to ensure that the object
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,