[英]Overriding an equals method from the java…Object class
我一直在試圖找出這個問題背后的原因,並且一直在努力尋找結果為何。 我將解釋我所理解的一切,希望有人能夠為我填補空白。
想象一下,您有一堂課:
public class Point {
public boolean equals(Object o) {
if (o == null || (!(o instanceof Point)) { // Let's call this method 1
return false;
}
Point other = (Point) o;
return x == other.x && y == other.y;
}
public boolean equals(Point p) { // Let's call this method 2
if (p == null) {
return false;
}
return x == p.x && y == p.y;
}
}
現在,我們創建以下對象:
Object o = new Object()
Point p = new Point(3,4)
Object op = new Point(3,4)
如果我們致電:
p.equals(o) // this calls method 1
p.equals(p) // this calls method 2
p.equals(op) // this calls method 1
但是,這是我感到困惑的地方。
op.equals(o) // this calls method 1
op.equals(op) // this calls method 1
op.equals(p) // this calls method 1
為什么最后一個調用方法1? 方法2的方法簽名不應該允許去那里的調用嗎?
如果有人可以向我解釋,那就太好了!
op
是Object
類型的變量,它沒有具有簽名public boolean equals(Point p)
。 因此,可以通過調用op.equals()
(無論參數類型如何op.equals()
執行的唯一equals
方法具有簽名的boolean equals (Object o)
。 您的Point
類將覆蓋boolean equals (Object o)
,因此在后三種情況下都將調用方法1。
鑒於
Point p = new Point(3,4)
Object op = new Point(3,4)
由於op
是一個Object
op.equals(p)
將調用equals(Object o)
方法,因為那是Object
擁有的唯一equals
方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.