I\'m following this MOOC on OOP in Java and it has presented an example I don\'t fully understand. In the example, a Book
class has been created and they are const
Because the compiler cannot (is forbidden to) infer that your previous type check was done for the purpose of eliminating improper object types before casting.
E.g., sometimes less is more: what if in the next statements you only need to cast your object to one of the base classes or implemented interfaces?
interface Authored {
public getAuthorName();
}
interface Publication {
public String getISBN();
};
public class Book
implements Authored, Publication {
// ...
public boolean equals(Object other) {
if (other == null) {
return false;
}
if (getClass() != other.getClass()) {
return false;
}
// on purpose, we use only the Publication interface
// because we want to avoid potential misspelling or missing
// title, author name, etc. impacting on equality check
// We'll consider ISBN as a key unique enough to
// determine if two books (e.g. registered in different
// libraries) are the same
Publication p=(Publication)other;
return this.getISBN().equals(p.getISBN());
}
}