tag:blogger.com,1999:blog-9236232.post110987102439589690..comments2023-10-29T19:14:49.183+05:30Comments on A tryst with Shetty: Bad usage of instanceofChirdeep Shettyhttp://www.blogger.com/profile/14381505283745664367noreply@blogger.comBlogger5125tag:blogger.com,1999:blog-9236232.post-1134460786267356812005-12-13T13:29:00.000+05:302005-12-13T13:29:00.000+05:30What if other is a descendant of MyClassName?What if other is a descendant of MyClassName?Anonymousnoreply@blogger.comtag:blogger.com,1999:blog-9236232.post-1123993012596963082005-08-14T09:46:00.000+05:302005-08-14T09:46:00.000+05:30I would rather use the following code in my equals...I would rather use the following code in my equals()<BR/><BR/>public boolean equals(Object other) {<BR/> if (this == other) return true;<BR/> if (null == other) return false;<BR/> <B>if (!this.getClass().getName().equals(other.getClass().getName()))<BR/> return false;</B><BR/> return equals((MyClassName)other);<BR/> }<BR/><BR/>This is much safer than using instanceOf. Esp. when you have multiple JVMs.Anonymousnoreply@blogger.comtag:blogger.com,1999:blog-9236232.post-1110102394024595992005-03-06T15:16:00.000+05:302005-03-06T15:16:00.000+05:30I agree with Micheal in using class equivalence ch...I agree with Micheal in using class equivalence checks in the equals method. <br />I guess I didn't realize the use of instanceof in serialization.Chirdeep Shettyhttps://www.blogger.com/profile/14381505283745664367noreply@blogger.comtag:blogger.com,1999:blog-9236232.post-1109959266880801582005-03-04T23:31:00.000+05:302005-03-04T23:31:00.000+05:30Binkley, I agree with your first point but as to y...Binkley, I agree with your first point but as to your second I think checking for class equivalence (getClass() == other.getClass()) is preferable to using instanceof in equals methods. Using instance in equals for non-final classes may make your equals method non-symmetric.<br /><br />E.g.<br />(new Base().equals(new Derived())<br />!=<br />(new Derived().equals(new Base())Anonymousnoreply@blogger.comtag:blogger.com,1999:blog-9236232.post-1109904334538225722005-03-04T08:15:00.000+05:302005-03-04T08:15:00.000+05:30instanceof is still needed. Two obvious situation...instanceof is still needed. Two obvious situations are serialization so that you can freeze/thaw the exact correct object and parameter narrowing where you need a more exact match than provided an interface or parents method signature.<br /><br />The best example of the latter is boolean equals(Object) where you want to respond to equals for any possible type, but need to narrow the parameter to your same type for checking equality.Brian Oxleyhttps://www.blogger.com/profile/06617364377560752378noreply@blogger.com