How to properly override equals.() method in Java
Posted on Aug 19, 2018 in Tutorial • 1 min read
When creating my first Java class, I was trying to override the equals()
method the way I created other methods in my own class. I passed in an other
object of my class and compared it with some normal if
statements. It failed.
It turns out there are specific rules to follow when overriding a Java method.
In the case of equals()
, the most important thing is that it must take an Object obj
(an instance of the Java Object class) as parameter instead of a MyClass other
.
public boolean equals(Object obj) {
...
}
It's good practise to first check if obj
is null.
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
}
Then check if this object is an instance of MyClass. (You can also use the instanceof
operator)
public boolean equals(Object obj) {
...
if (!MyClass.class.isAssignableFrom(obj.getClass())) {
return false;
}
}
Finally, if it passes the checks, cast it into MyClass
with a final
statement and you can carry on with the checks you with to perform.
public boolean equals(Object obj) {
...
final MyClass other = (MyClass) obj;
...
}