You are right that some types are considered incompatible and cannot be legally compared with instanceof. At least, not with references that identify the incompatible types - you could always use two Object references to compare anything you want. But - are a Robot and Animal really incompatible? Is there no possible way to create an object that is both a Robot and an Animal?
The answer given in the K & B book is correct.
As per your reference in the line 15 it will check the reference variable is not an instance of Animal it return false so the sysout will not print.
It does not give any cmpiler error.
James Boswell wrote:Sorry, could someone confirm what the correct answer is for the original question asked in this thread? Thanks
the main question was regarding whether or NOT compiler error comes when using instanceof operator. consider this example
s instance of java.utilDate; // here is is of type java.util.String
the answer would be compiler error. why ? since String and Date are in different hierarchies in java class hierarchy. had 's' be of the type Object ,the compiler would have passed it, though it would fail at runtime.
now consider this code snippet
rob instanceof Animal; // why compiler does not flag error here like it did in the above case, this was the original question. mansi's(question poster) doubt was that it should give compiler error since robot and animal are not in same hierarchy(like it was in string and date case above).
i think the link given by karthikeyan explains the reason very well with extra information.
if you still have doubts James, feel free to post.
if you look into the previous posts, you will come to know that original question was not really regarding choice. it was beyond that , in that whether the code will even compile. if you want to know the correct answer you can simply run it and find it out for yourself. though the link given by karthikayen has good food for thought and knowledge.
subject: Use of instanceof operator K&B Practise Exam 3 Q-35