Nicholas Dry Nicholas Dry - 1 year ago 43
Java Question

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!

Answer Source

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.