Overriding the equals() method

Now, let's implement the equals() method:

class PersonWithEquals{
private int age;
private String name;
private String hairstyle;

public PersonWithEquals(int age, String name, String hairstyle) {
this.age = age;
this.name = name;

this.hairstyle = hairstyle;
}

@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
PersonWithEquals person = (PersonWithEquals) o;
return age == person.age && Objects.equals(name, person.name);
}
}

Notice that, while establishing the objects' equality, we ignore the hairstyle field. Another aspect that requires comments is the use of the equals() method of the java.utils.Objects class. Here is its implementation:

public static boolean equals(Object a, Object b) {
return (a == b) || (a != null && a.equals(b));
}

As you can see, it compares references first, then makes sure that one is not null (to avoid NullPointerException), then uses the equals() method of the java.lang.Object base class or the overriding implementation that might be present in a child passed in as a parameter value.  In our case, we pass in parameter objects of type String that do have the equals() method implemented, which compares String type values, not just references (we will talk about it shortly). So, any difference in any field of objects, PersonWithEquals, will cause the method to return false.

If we run the test again, we will see this:

PersonWithEquals p11 = new PersonWithEquals(42, "Kelly", "Ponytail");
PersonWithEquals p12 = new PersonWithEquals(42, "Kelly", "Pompadour");
PersonWithEquals p13 = new PersonWithEquals(25, "Kelly", "Ponytail");
System.out.println(p11.equals(p12)); //true
System.out.println(p11.equals(p13)); //false
System.out.println(p11 == p12); //false
p11 = p12;
System.out.println(p11.equals(p12)); //true
System.out.println(p11 == p12); //true

Now, the equals() method returns true not only when references are equal (so they point to the same object), but also when the references are different but the objects they refer to have the same type and the same values of certain fields that are included in the object identification.