I'm learning Java language and I have one question for you.
For example: I have a class Employee like this:
public class Employee {
private int id;
private String name;
public Employee(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
}
So I should write method equals() like:
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Employee employee = (Employee) o;
return id == employee.id && Objects.equals(name, employee.name);
}
or
@Override
public boolean equals(Object o) {
if (super.equals(o)) return true;
if (o == null || getClass() != o.getClass()) return false;
Employee employee = (Employee) o;
return id == employee.id && Objects.equals(name, employee.name);
}
My book says:
if you redefine the equals method in a subclass, use super.equals(other).
but all classes extends Object class so which version of this method is better? I think that the first option will be faster (CPU). And the first method is the most popular, but why?
It actually depends on the requirement. I'm elaborating.
Suppose, your requirement is to be equal with another object, parents needed to be equal as well, you should use
if (super.equals(o)) return true;
The topmost class in the inheritance tree will use
if (this == o) return true;
then. Though, if you keep the same as its child class, it will call the Object class's equals() which checks reference, so still same output with another extra calling.
Here instead of calling parent class equals() you could compare parent class fields directly in the subclass. But think that, in the future, if your business doesn't need some field from the parent class, and tells you that to remove that field from the parent class, you will need to delete it in subclasses as well. So to reduce that extra coding, better don't use the parent class field in the subclass's equals() method to compare equality.
But if the requirement is just a specific class needs to be considered to get equality, then you can use
if (this == o) return true;
without any problem.