|
Is the following OK? Object obj; String str = "Yertle" ; obj = str; ((YouthBirthday)obj).greeting(); A good answer might be:No. | |
The instanceof OperatorA 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. 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:variable instanceof Class
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. | |
QUESTION 17:If you don't know in advance what classes a variable might hold, will instanceof help? Click Here after you have answered the question |