Is the following OK?
Object obj; String str = "Yertle" ; obj = str; ((YouthBirthday)obj).greeting();
No. A type cast does not change anything. It merely tells the compiler what is expected.
instanceof
OperatorObject obj; YouthBirthday ybd = new YouthBirthday( "Ian", 4 ); String str = "Yertle"; obj = ybd; if ( obj instanceof YouthBirthday ) ((YouthBirthday)obj).greeting(); else if ( obj instanceof String ) System.out.print( (String)obj );
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.
The instanceof
operator evaluates to true
or false
depending on whether the variable refers to an object of
its operand.
variable instanceof Class
Also, instanceof
will return true
if variable
is a descendant of Class
.
It can be a child, a grandchild, a greatgrandchild, or ...
of the class.
For example in the above fragment,
instanceof
is used to ensure that the object
pointed to bye obj
is used correctly.
Will the following work?
Object obj; YouthBirthday ybd = new YouthBirthday( "Ian", 4 ); String str = "Yertle"; obj = ybd; if ( obj instanceof Card ) // Note changes here ((Card)obj).greeting(); else if ( obj instanceof String ) System.out.print( (String)obj );