bm1125
bm1125

Reputation: 223

using equal() method on two different objects with same attribute

Say I have two Classes A & B with no relationship between them and both have the same attribute private int _x

then I set the following method for A:

public boolean equals (A other) {
    return ((other!=null) && ( _x == other._x));
}

and B :

public boolean equals (Object other) {
    return ((other!=null) && (other instanceof B) && (_x = ((B)other._x));
}

Now if I apply the following

B z1 = new B(10);
Object z2 = new A(10);

System.out.print(z1.equals((A)z2);

I would expect to get true as the compiler decide which method to run according to the type of the object inserted(!) and not the pointer .

I know this website is less about theory but if someone could just comment and tell me why I get false running this code?

Upvotes: 0

Views: 86

Answers (1)

Eng.Fouad
Eng.Fouad

Reputation: 117597

System.out.print(z1.equals((A)z2);

This prints false because other instanceof B evaluates to false in B#equals implementation:

public boolean equals (Object other) {
    return ((other!=null) && (other instanceof B) && (_x = ((B)other._x));
                             ^^^^^^^^^^^^^^^^^^^^
}

Upvotes: 2

Related Questions