you are trying to compare a Set (aa is a Set not Integer) and a Number. This is allowed as Set is an interface and Number is a non-final class. So in some cases, a Set might be a Number as there can be a class which implements Set and extends Number. But when you compare Set (i.e. aa) and Integer, it is not allowed as Integer is a final class. So in no way can aa be an instaceof Integer. Same is the case with Byte...
So Ankit are you saying that if it is a final class then you cannot use the instanceof operator? I mean String is a final class but I would assume that you can use the instanceof on a String object. Pardon me if I asked a very basic questio. Thanks, Meera
as Number is a non-final class, any class can implement Set and extend Number, in which case, all of these three fall in same inheritance hierarchy. So, instanceOf operator works fine.
but nowhere in the inheritance tree of Integer, Set is implemented and again, Integer can not be extended as it's a final class. So, it's not possible to create a class which implements Set and extends Integer, both. Therefore use of instanceOf operator with Set and Integer will produce compile time error.
When it's obvious that you have to do it, just do it without shattering your thoughts over different directions.
Originally posted by meera kanekal: Yes I did, and I get a compiler error. So the same explanation holds true for String as well. So am I correct in saying that you cannot use "instanceof" test on final classses? Thanks, Meera
No. It is not correct. Of course, you can use the instanceof operator with final classes.
The issue here is with the ability to determine the result at compile time, and determined it as false. If, at compile time, the compiler can guarrantee that there is no way that the object is an instance of a particular class or interface, it will report it as a failure at compile time.
And how the compiler makes such a determination is based on the reference type being checked, the type it is checking, and/or whether these types are final or not.
Henry [ December 07, 2008: Message edited by: Henry Wong ]