There should be no problem, provided you also override hashCode()
, and provided the properties in question are immutable.
An equals()
method that sometimes returns true and sometimes returns false, depending on whether someone has called setXXX()
in the mean time, is a very dangerous thing -- it can't be used for much of what equals()
is good for, such as determining membership in a collection.
If equals()
is really what you need -- in order to work with other APIs like java.util.Collections
-- then I suggest overriding the mutators to throw UnsupportedOperationException
. If not, your equals()
method will be unreliable. See for example: How to use two numbers as a Map key
If you can't -- e.g. if the mutators are final
-- then I wouldn't even try subclassing. Instead, I'd copy the values from the 'superclass' object into my own fields, and then throw the original away. (If you keep it around, even as a private field, you can't count on somebody else not having a reference to it and mutating it.) If you need your 'subclass' to interoperate with APIs that require the 'superclass', then include an asXXX()
method that generates the "superclass" object on the fly.
Otherwise, if you just need to determine equivalency for your own purposes, I wouldn't override equals()
/hashCode()
at all, but instead create a new method, and call it something like isEquivalentTo()
.