How equals method behaves when overloaded?

sid :

So I have below Test code Implementation

class Employee{
     String name;
     int age;

    @Override
public boolean equals(Object obj) return false;

public boolean equals(Employee obj) return true;     
}

And in the main method, I have below code

public static void main(String[] args) {        
    Object E1 = new Employee();
    Employee E2 = new Employee();

    System.out.println(E1.equals(E2));

}

So as per my understanding, polymorphism should bind E1 with method equals(Employee obj) as I am passing the object of type Employee and E1 instance is also of type Employee (though reference to Object underlying instance is of type Employee). However, I see that it prints false, which means equals(Object obj) has been invoked(Same has been verified using Sysout statement in both equals method).

Sweeper :

Your understanding of how binding is done is incorrect.

There are two steps in binding:

  1. Decide which overload to call
  2. Decide which implementation to call.

The first step is done at compile time and is based on the compile-time type of the variable. The second step is done at runtime and is based on the runtime type of the object. The second step is what you refer to as "polymorphism".

During the first step, E1's compile time type is Object, so there is only one overload of equals to choose from - equals(Object). Therefore, that overload is chosen.

During the second step, there are two implementations to choose from:

// In Employee class:
public boolean equals(Object obj) return false;

// In Object class
public boolean equals(Object obj) {
    return (this == obj);
}

Since E1's runtime type is Employee, as you have correctly identified, it chooses the implementation in the Employee class, which returns false all the time.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=145277&siteId=1