View RSS Feed

My Java Tips

Using Instanceof operator in java

Rate this Entry
by , 11-08-2011 at 04:16 PM (1540 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




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...");

}
Here "instanceof" operator should be used but if both Dog and cat class have method eat then using "instanceof" operator is useless.

Submit "Using Instanceof operator in java" to Facebook Submit "Using Instanceof operator in java" to Digg Submit "Using Instanceof operator in java" to del.icio.us Submit "Using Instanceof operator in java" to StumbleUpon Submit "Using Instanceof operator in java" to Google

Tags: None Add / Edit Tags
Categories
Java SE

Comments