Using Instanceof operator in java
by , 11-08-2011 at 04:16 PM (1127 Views)
Good Java 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
Here "instanceof" operator should be used but if both Dog and cat class have method eat then using "instanceof" operator is useless.Java Code:if (mobj instanceof Dog) { return (Dog)mobject.run(); } else if (mobj instanceof Cat) { return (Cat)mobject.walk(); } else { System.out.println("Unknown animal..."); }









Email Blog Entry
MU Tân D?nh Season 7 - Open Beta...
Today, 03:42 PM in Java Software