The instanceof operator gives you the runtime type of an object pointed to by an object reference. It has 2 arguments objectReference instanceof ClassName In the code below, I tried generating random instances and tried to determine the runtime type using instanceof. I used getClass() to verify the results:
It doesn't have to be the exact runtime type. A superclass type will return true as well (this was also demonstrated in the program above). That is, if the object reference x referred to an object of type SubClass, x instanceof SuperClass will return true as well, since, by inheritance, a SubClass object is a SuperClass object as well ("a cat is also a mammmal"). This is also true for interface types x instanceof SomeInterface will also return true since SomeInterface is a supertype of x. The code above implies this, since the return value of generateInstance does not throw a ClassCastException.
Joined: Aug 27, 2002
hi! thanx for the example. in the whoIAm() method of PeerClass suppose i add this instanceof SubClass then compile error results. but when i write in main()
SomeInterface i=new PeerClass(); System.out.println(i instanceof SubClass); there is no error why? madhur.
in the whoIAm() method of PeerClass suppose i add this instanceof SubClass then a compile error results.
Because PeerClass isn't "hierarquically" related to Subclass. That is, nor PeerClass is a supertype of SubClass, neither SusClass is a supertype of PeerClass.
but when i write in main() SomeInterface i=new PeerClass(); System.out.println(i instanceof SubClass); there is no error
Because SomeInterface is a supertype of SubClass. Notice that the compiler will complain in the same manner as it would do with a cast expression. Also the compiler would only check the compile type of the expressions, not the runtime type. I like to call it the declared type. The declared type of the variable i is SomeInterface. The declared type of this within a instance method is the class where the method is. In our example the declared type of this is PeerClass.
Hi There: I changed following statement: SomeInterface i = (SomeInterface) generateInstance(); to SomeInterface i = generateInstance(); Still I am getting same results. So can we safely conclude that instanceof provides the original type of the object when created. It does not report declared type or converted type. Thanks Barkat
Joined: Jul 03, 2001
You are right Barkat. However your example doesn't change anything because the declared type of i in "SomeInterface i = generateInstance();" is still SomeInterface. Think of "variable instanceof Type" as you would do of "(Type) variable" regarding the following: a) The compiler will complain if the declared type of variable (aka compile type) isn't "hierarquically" related to Type. b) At runtime both find out the type of the object pointed by the variable (aka runtime type) [ September 02, 2002: Message edited by: Jose Botella ]