What is the result of compiling the following class?
public class Book { private int ISBN; private String title, author; private int pageCount; public int hashCode() { return ISBN; } /* w w w . java 2 s .c om*/ @Override public boolean equals(Object obj) { if ( !(obj instanceof Book)) { return false; } Book other = (Book) obj; return this.ISBN == other.ISBN; } // imagine getters and setters are here }
hashCode()
is incorrect.equals()
does not override the parent method correctly.equals()
tries to refer to a private field.A.
hashCode()
is correct and perfectly reasonable given that equals()
also checks that field.
ClassCastException is a runtime exception and therefore does not need to be handled or declared.
The override in equals()
is correct.
It is common for equals()
to refer to a private instance variable.
This is legal because it is within the same class, even if it is referring to a different object of the same class.