一个 Employee 类的大致结构:
public class Employee {
...
// Override
public boolean equals(Object otherObject) {
System.out.println("Choose parent");
...
}
// Overload
public boolean equals(Employee otherObject) {
System.out.println("Choose child");
...
}
}
一个测试类:
public class EmployeeTest {
psvm {
Employee e1 = new Employee("lee", 3000, 1999, 10, 1);
Employee e2 = new Employee("lee", 3000, 1999, 10, 1);
Object obj1 = e2;
System.out.println(e1.equals(obj1)); // 1.result: Choose parent
System.out.println(obj1.equals(obj1)); // 2.result: Choose parent
System.out.println(obj1.equals(e1)); // 3.result: Choose parent
System.out.println(e1.equals(e1)); // 4.result: Choose child
}
}
根据 dynamic binding,四个语句都会调用 Employee 中的方法,然后再根据 overloading resolution 进行参数匹配,我的猜想是 1, 2 会匹配 Object otherObject 参数,3, 4 会匹配 Employee otherObject 参数,但实际 3 的匹配和我的设想不一样,我以为这和方法定义的顺序有关,调换了之后并没有用;
Core Java 里面说 overloading resolution 的时候提到:
The situation can get complex because of type conversions (int to double, Manager to Employee, and so on).
所以到底是怎么个回事情...