p.equals(q) 調用時,equals 方法內的 this 指向 p,參數 obj 指向 q。強轉後 st 也指向 q,比較的是 p 與 q 的字段值。
main:
Student p = new Student(); p.name="xyz"; p.age=13;
Student q = new Student(); q.name="xyz"; q.age=13;
p.equals(q); // 調用點
equals 內部:
public boolean equals(Object obj) {
// this → p, obj → q
Student st = (Student) obj; // st → q
return this.name == st.name && this.age == st.age; // 比較 p 與 q 的字段
}
equals,this 就是誰。instanceof 守衛 + 強轉。== 比較 String,僅比較引用地址。**正確應用 Objects.equals(name, st.name) 或 name.equals(st.name)**。@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Student that = (Student) o;
return age == that.age && Objects.equals(name, that.name);
}
@Override
public int hashCode() {
return Objects.hash(name, age);
}
「誰調用 equals 方法 this 就是指的誰。」—— 多態動態綁定的核心體現。