I want to compare the stats for two people using a custom made equals method that will override the equals method in the Object class. Since the return type of this equals method will be a boolean, I know that I need to pass in the (Object obj) parameter. As I define the new equals method, I was taught that I need to first do a check that the obj class does not match the instance class. Once that is verified, I type-cast the obj class to the instance class, and can carry on with the rest of the code.
However, I do not understand why I need to verify that the obj class does not match the instance class. I thought the two classes are supposed to not match, hence the need for the type-cast.
Can anybody tell me why we need to verify that the obj class does not match the instance class? The code I am working on is written below.
public boolean equals(Object obj) {
if (obj == null || obj.getClass() != this.getClass())
return false;
else {
Person pp2 = (Person) obj;
if (this.name.equals(pp2.name) && this.age == pp2.age)
return true;
else
return false;
}
}
public static void main(String[] args) {
Person ps1 = new Person("Buddy", 14);
Person ps2 = new Person("Buddy", 14);
if (ps1.equals(ps2))
System.out.println("Same");
}
What you suggest to do is that:
public boolean equals(Object obj) {
Person pp2 = (Person) obj;
return (this.name.equals(pp2.name) && this.age == pp2.age);
}
This would violate the equals()
method contract, which clearly says that the method must return false when the two objects are not considered equal. That would not be the case here: the method would throw a ClassCastException
instead (or a NullPointerException
if obj is null).