Using Instanceof operator in java
30 March 2007GoodJava programmers use “instanceof” operator since it is a must to escape from “Class Cast Exceptions”.
Following are the key points to be remembered while using instanceof operator
- Instanceof operator is used to restore full functionality of an object.
- While programming many times heterogeneous collection are used and then to invoke full functionality of an object casting is required then to check the type of instance, “instanceof” operator can be used.
- “instanceof” operator loads class in jvm making it a heavy operation so it is desirable to avoid it, If you can use overridden method instead.
See following code sample
if (mobj instanceof Dog) { return (Dog)mobject.run(); } else if (mobj instanceof Cat) { return (Cat)mobject.walk(); } else { System.out.println("Unknown animal..."); }
Here “instanceof” operator should be used but if both Dog and cat class have method eat then using “instanceof” operator is useless.
Related Posts:
Top Of Page | Trackback
If you found this page useful, consider linking to it. Simply copy and paste the code below into your web site.
It will look like this: Using Instanceof operator in java