Java ProgramsOOPequals() Override

equals() Override in Java

intermediate·  OOP  ·  Object Class

Problem

The default equals() inherited from Object only returns true when two references point to the exact same object; overriding it lets two separate objects be considered equal based on what they actually contain.

Create a Person class where two different objects with the same name and age are considered equal.

Input
new Person("Alice", 30).equals(new Person("Alice", 30))
Output
Equal: true

Java Program

Java
public class Person { private String name; private int age; public Person(String name, int age) { this.name = name; this.age = age; } @Override public boolean equals(Object o) { if (this == o) return true; // same reference — trivially equal if (o == null || getClass() != o.getClass()) return false; // null or different type can't be equal Person other = (Person) o; return age == other.age && name.equals(other.name); // compare actual field values } public static void main(String[] args) { Person p1 = new Person("Alice", 30); Person p2 = new Person("Alice", 30); System.out.println("Equal: " + p1.equals(p2)); } }

Output

Equal: true

Core Logic

Comparing the actual name and age fields of two Person objects, instead of comparing their memory references, is what lets separately-constructed objects be recognized as equal.

How It Works
  1. 1if (this == o) return true; short-circuits immediately when both references already point to the same object.
  2. 2if (o == null || getClass() != o.getClass()) return false; rules out null and any object that isn't also exactly a Person, before it's safe to cast.
  3. 3After casting o to Person, the fields are compared directly: age == other.age && name.equals(other.name).
  4. 4Only when both the name and age match do two Person objects count as equal — everything else about how they were constructed is irrelevant.
new Person("Alice", 30) and a second, separately-constructed new Person("Alice", 30) are two different objects in memory, but equals() reports them as true since their fields match.
💡

Key Point: The default Object.equals() would have reported these same two objects as unequal, since it only ever compares references — overriding equals() is what makes value-based comparison possible at all.

Key Concepts

@Overrideequals()value equality vs reference equality

Related Programs