When writing one's own classes, is it always necessary to override equals(Object o)
?
If I don't, will it automatically check that all the fields are the same? Or does it just check if the two variables point to the same object?
If one is writing a class that is going to have its objects be compared in some way, then one should override the equals
and hashCode
methods.
Not providing an explicit equals
method will result in inheriting the behavior of the equals
method from the superclass, and in the case of the superclass being the Object
class, then it will be the behavior setforth in the Java API Specification for the Object
class.
The general contract for providing an equals
method can be found in the documentation for the Object
class, specifically, the documentation of the equals
and hashCode
methods.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With