There is an Employee class and a class called Manager that extends Employee. The two have same fields, but Manager has one extra field called bonus. The equals method for Manager is:
public boolean equals(Object otherObject){ if(!super.equals(otherObject) return false; Manager other = (Manager) otherObjetc; return this.bonus == other.bonus; } We create employeeObj and managerObj as an instance of Employee and Manager class respectively, such that all their fields are identical (except the bonus which employeeObj doesn't have at all).
Then if we call the managerObj.equals(employeeObj) does the if condition return false? if the answer is 'no', then do we get any error for the cast or the line after it because employee doesn't have a bonus field?
The book that this example is from claims that super.equals checks if this and otherObjetc belong to the same class. But I think they didn't take into account that the method will throw exception if we pass to it an instance of employee class. Correct me if i am wrong...
Here is the equals method for employee class:
public boolean equals (Object otherObjetc){ if (this==otherObjetc) return true; if (otherObject == null) return false; if (getClass() != otherObject.getClass()) return false; Employee other = (Employee) otherObject; return name.equals(other.name) && salary==other.salary }
employeeObj.equals(managerObj)may return true, butmanagerObj.equals(employeeObj)will always return falsea.equals(b)andb.equals(a)must return the same result. So if Manager extends Employee, then a Manager can be used in place of an Employee without error thanks to polymorphism. The above code, while it will compile and run, is invalid because it violates the contract of the equals method.superimplementation please.a.equals(b)butb.notEquals(a)issue coded into the equals method above. (Because compareTo() and hashCode() are written to return consistent results with equals() right?)