简体   繁体   中英

Overriding an equals method from the java…Object class

I've been attempting to figure out the rationale behind this question and I have been struggling to see why the outcome is what it is. I will explain everything I understand and I hope someone will be able to fill in the blanks for me.

Imagine you have a 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;
    }
}

Now we create the following objects:

Object o = new Object()

Point p = new Point(3,4)

Object op = new Point(3,4)

If we call:

p.equals(o) // this calls method 1

p.equals(p) // this calls method 2

p.equals(op) // this calls method 1

However, this is where I get confused.

op.equals(o) // this calls method 1

op.equals(op) // this calls method 1

op.equals(p) // this calls method 1

Why does the last one call method 1? Shouldn't the method signature of method 2 warrant the call to go there?

If anyone could explain it to me that would be great!

op is a variable of type Object , which has no method having the signature public boolean equals(Point p) . Hence the only equals method that can be executed by calling op.equals() (regardless of the argument type) has the signature boolean equals (Object o) . Your Point class overrides boolean equals (Object o) , so your method 1 is called in all of the latter 3 cases.

Given that

Point p = new Point(3,4)
Object op = new Point(3,4)

and since op is an Object

op.equals(p)

will call the equals(Object o) method, because that's the only equals method that Object has.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM