Sobes.tech
Junior — Middle

Можно ли применять метод equals без его предварительного переопределения в классе?

sobes.tech AI

Answer from AI

Yes, the equals method can be used without overriding it, as it is inherited from the Object class. However, in this case, the behavior of the method will be standard: comparing references to objects (i.e., checking whether two variables point to the same object in memory).

If you need to compare objects by content (for example, by field values), then the equals method should be overridden in the class. Without overriding, the comparison will not work as expected for logically equal objects.

Example:

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

Person p1 = new Person("Alice");
Person p2 = new Person("Alice");

System.out.println(p1.equals(p2)); // false if equals is not overridden

To make content-based comparison work, you need to override equals and hashCode.