I've been doing the MOOC Java programming course and they typically override equals like this:
I'm just a bit confused about step 2 and 3.
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;
}
Because you’ve only compared the dynamic type; the static type of comparedObject
is unchanged: it’s Object
, and you cannot access its Book
members (think about it: at this point you know that the dynamic type of comparedObject
is Book
; but the Java compiler still sees it with its declared type). To make the compiler understand that the object type is Book
, you first need to create an object whose static type is Book
, and to do that you need a cast.
The static type information is what the Java compiler sees, and which is what the compiler uses to check whether your code is statically correct.