How to correctly override equals() method in Java?

That’s a solid implementation, @akanshasrivastava.1121! One way to make it even more readable and null-safe is by using Objects.equals() from Java’s java.util package. It automatically handles null checks, making the code cleaner and safer.

Here’s the improved version:

import java.util.Objects;

@Override
public boolean equals(Object obj) {
    if (this == obj) return true;
    if (obj == null || getClass() != obj.getClass()) return false;

    People other = (People) obj;
    return Objects.equals(name, other.name) && Objects.equals(age, other.age);
}

:white_check_mark: Why use this?

  • No need for explicit null checks—Objects.equals() does it for you.
  • More readable, especially when comparing multiple fields.

:bulb: This approach enhances your java override equals implementation with better readability and safety.