public class Person {
private String name;
public Person(String name){
this.name = name;
}
public String getName() {
return name;
}
public boolean equals(Object other) {
Person person = (Person)other;
System.out.println("执行复写方法");
return this.name.equals(person.getName());
}
public boolean equals(Person other) {
System.out.println("执行重载方法");
return this.name.equals(other.getName());
}
}
public class PersonTest {
public static void main(String[] args) {
Person p = new Person("李磊");
Person other = new Person("陈尚");
p.equals(other);
}
}
程序运行时调用的是参数为Person的equals方法,当将参数为Person的equals方法注释后,会调用参数为Object的方法。
为什么不是优先调用参数为Object的方法?
既然两种参数的equals方法都能被调用,那么,为什么不会报错?程序应该不知道具体调用哪一个方法才对
Object p = new Person("李磊");
Object other = new Person("陈尚");
p.equals(other);
楼主再这样比较一下应该就明白了。
public boolean equals(Person other)
p.equals(other);当然调这个,other是Person好不好
Object参数的是重写父类的方法
Person参数的是重载equals方法
两个方法参数不一样,当然不报错,具体调用得看调用得参数,按照你的测试,你new的就是person对象,当然调用的就是equals(Person other)