0
public class Person {

    private String name;

    public Person(String name) {
        this.name = name;
    }

    public boolean equals(Person p) {
        System.out.println("..............");
        return p.name.equals(this.name);
    }
}

Hi, I was going through OCJP question and answer and answer to this question was The equals method does NOT properly override the Object.equlas method.

I think it is redundant to override here with name which is String but this answer to this question is also not correct.

Could you please point out what concept i am missing here...

Note: There are no option saying override hasCode and equlas with same parameter to this question...

Tommaso Bertoni
  • 2,333
  • 1
  • 22
  • 22
Rajesh Kumar
  • 41
  • 1
  • 6

2 Answers2

13

The signature of equals should be :

public boolean equals(Object p)

Your public boolean equals(Person p) method doesn't override Object's equals. It overloads it.

A possible implementation :

@Override
public boolean equals(Object other)
{
    if (!(other instanceof Person))
        return false;
    Person p = (Person) other;
    return p.name.equals(this.name);
} 
Eran
  • 387,369
  • 54
  • 702
  • 768
  • public boolean equals(Object p){return ((Person)p).name.equals(this.name);} This is the correct signature right? – Rajesh Kumar Mar 05 '15 at 14:37
  • 1
    @RajeshKumar: [ClassCastException](http://docs.oracle.com/javase/7/docs/api/java/lang/ClassCastException.html) – Voicu Mar 05 '15 at 14:39
  • @RajeshKumar Not quite. Before casing `p` to `Person`, you should validate that it's actually an instanceof Person. – Eran Mar 05 '15 at 14:39
  • @LocHa If `name` may be null, you have to test for that scenario and return a proper value, but I'm assuming that a Person without a name is not a possible scenario (the constructor of Person should contain a validation that would prevent that). – Eran Mar 05 '15 at 14:55
7
@Override
public boolean equals(Object ob) {

    if (!(ob instanceof Person)) {
        return false;
    }

    Person p = (Person)ob;

    return p.name.equals(this.name);
}

ClassCastException proof
NullPointerException proof (Is null check needed before calling instanceof)

Community
  • 1
  • 1
Tommaso Bertoni
  • 2,333
  • 1
  • 22
  • 22