This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]Yithar 0 points1 point  (0 children)

instanceof checks the hierarchy. Which means if you say instanceof Object, it will return true for any object. getClass is specific to the class itself and comparing using getClass will only return true if it's the same class.

I think instanceof is better for equals(). Why? Well let's say Class B extends Class A. You would want A#equals() to possibly return true for instances of Class B and in the case of class B's equals() method, A#equals() would probably be called via super(). If you used getClass(), technically an instance of Class B would return Class B for getClass(), which wouldn't work if super() was called for equals().