Question about comparing objects (java) via /r/learnprogramming

Question about comparing objects (java)

I'm just starting to learn about inheritance with university of helsinki mooc part two and they're explaining how when we create our own objects they inheirit the properties of the object class defined by the API and I'm not understanding one part of their explaination. It states that when you are comparing two objects that are of your own creation they don't have their own equals method implementation (that makes sense, that isn't difficult to understand) so then it goes on to say that if you want to compare the values of the two objects then you must create your own implementation of the inheirted equals method (again that makes sense). They then go on to develop the code for comparing two objects using the equals method, here it is :

public boolean equals(Object object) { if (object == null) { return null; } if (getClass() != object.getClass()) { return false; } Book compared = (Book) object; if (this.publishingYear != compared.getPublishingYear()) { return false; } 

return true; }

Ok so here's where I can't follow the logic. Why is it necessary to cast the object in which you're trying to compare into the starting object's type when taking into consideration the code posted above, the type of the compared object would already have to be the same type as the object on which the method is acting because if they weren't the same, the code could never reach that portion of the code in the first place. Could any of you guys explain to me why the object has to be casted into a book object and could you explain to me the flaw in my logic that would make the casting unecessary?

All insight is greatly appreciated. Thank you in advance.

Submitted July 16, 2017 at 02:26PM by PancakeBloat
via reddit


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s