user8194594
user8194594

Reputation:

java - equals method

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
}

Upvotes: 0

Views: 779

Answers (2)

SLaks
SLaks

Reputation: 887275

If you cast an object that is not a Manager to Manager, you will get an exception.

This is why Java is type-safe.

Upvotes: 0

Naman
Naman

Reputation: 31868

Then if we call the managerObj.equals(employeeObj) does the if condition return false?

Yes, it shall 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?

No, you wouldn't get a ClassCastException, since

if(!super.equals(otherObject)) return false; 

completes the execution and returns anyway and you do not reach

Manager other = (Manager) otherObject;

which can possibly throw a class cast exception.

Test code with some sample fields defined in the Employee and Manager models:

Employee employee = new Employee();
employee.setName("null");
employee.setSurname("pointer");
Manager manager = new Manager();
manager.setName("null");
manager.setSurname("pointer");
manager.setBonus(10);
System.out.println(manager.equals(employee));

Edit: The reason why

!super.equals(otherObject) 

evaluates to true and ultimately return false is because within equals of its super class

if (getClass() != otherObject.getClass()) return false;

getClass() (evaluates to Manager) and otherObject.getClass() (evaluates to Employee) are both difference classes.

Upvotes: 1

Related Questions