I have two classes Class1 and Class2,
Class1 obj;
Class2 obj1;
How can I compare obj is instance of Class2 ?
I am not able to use instanceOf operator for these classes, It is giving compilation error “cant’t compare incompatiable types”
I have two classes Class1 and Class2, Class1 obj; Class2 obj1; How can I
Share
If it’s failing at compile time, you can be sure that it would always fail at run time. The compiler won’t allow you to use
instanceofon two types where the first can’t be an instance of the second. e.g.:The compiler knows definitively that an Integer can never be a String because they’re not in the same inheritance hierarchy. Therefore it won’t even let you write it. If you’re tempted to write it anyway, then there’s something wrong with your design and/or your logic.
That being said, Class.isAssignableFrom() is another way to check inheritance hierarchies that can only fail at runtime:
It bears repeating that, while the above will compile successfully, the condition still can never be true. It only makes sense to compare types when they’re in the same inheritance hierarchy. For instance, this is a sensible comparison to make:
If you’re tempted to write code like this, though, it almost always means that you’ve broken polymorphism in your code, since this is exactly the sort of thing it’s supposed to handle.