He clearly said create an equals()
method, and you got it right here as well. But even after all this you created a method named instanceOf()
. Why?
Moreover, you may get a ClassCastException on this line, in case some other type of object is passed.
if ((Position)a instanceof Position)
Which means, precisely, that you should only cast the object
to Position
, after making sure that the object
passed is of type Position
. Which means now its good to go further with comparison. If its not of type Position
in the first place, then why should you bother comparing it further. Because it can never be equal. I hope you are getting my point.
[Edited to answer the question in comment]
Well, the actual instance should be of type Position. Once we know that its of type Position using instanceof operator, we know its safe to cast it to type Position from type Object. Now the question is why we need to cast? Because initially the instance was of type Object, and we were not sure about the actual type. You might already know that in Java you can assign any type to Object type, because Object is a parent of every class in Java. Hence, before applying instanceof we were not sure about the type of instance.
In case, you don't cast it, you will never be able to access its properties, namely, x, y, and id. You can try accessing any of these on actual object without casting. You will know you can't. Hence, you can't compare those either. I hope, this made it clear.