I've been doing the MOOC Java programming course and they typically override equals like this:
- If addresses of the 2 objects are the same = return true.
- If compared object is not an instance of the same class as the first object = return false.
- Convert the object to the same type as the one being compared to
- Compare the variables of each object - returns true or false
I'm just a bit confused about step 2 and 3.
- Step 2 checks if the 2nd object is an instance of the same type as the one its compared to...
If it isn't, the method ignores the rest of the code and returns false
If it is, we convert it to that Class. So at this point i'm confused about why we need to convert an object that is already an instance of the same class - to that class? If Java recognises it is of the same type, why do you need to convert it?
*Example below:
public boolean equals(Object comparedObject) {
// if the variables are located in the same place, they're the same
if (this == comparedObject) {
return true;
}
// if comparedObject is not of type Book, the objects aren't the same **
if (!(comparedObject instanceof Book)) {
return false;
}
// convert the object to a Book object
Book comparedBook = (Book) comparedObject;**
// if the instance variables of the objects are the same, so are the objects
if (this.name.equals(comparedBook.name) &&
this.published == comparedBook.published &&
this.content.equals(comparedBook.content)) {
return true;
}
// otherwise, the objects aren't the same
return false;
}