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
}