I have a simple base class, which is later extended by many separate classes, which potentially introduce new fields, but not necessarily. I defined an equals method in the base class, but also overriden that for a few subclasses. Is it OK to mix definitions in base/subclasses? In my case it was to avoid code duplication checking the same fields.
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
Quite a valid approach. The issue is in one of your subclasses it must retain the definition of equals as is bound by its parent. Else you have a broken equals function, which can cause some very unique scenarios during run time.
Take a look at "Implementing equals() To Allow Mixed-Type Comparison" from Angelika Langer .
Here is a brief explanation of some problems and a possible solution:
The equals contract says (amongst others):
That means you might get problems if your sub class is introducing new fields and you're comparing an object of the base class (or another sub class that doesn't override equals) to an object of this sub class.
Do NOT do the following:
because you get
A possible solution:
Replace the
instanceof
-check with a class comparison:With this solution an object of
BaseClass
will never be equal to an object of any subclass.If you create another
SubClass
without an@Override
of theequals
method, twoSubClass
-objects can be equal to each other (if theBaseClass.equals
check decides so) out of the box, but aSubClass
-object will never be equal to aBaseClass
-object.A good implementation could be as follows:
Please refer to the article mentioned above for more advanced problems and their solutions.
I guess, That's perfect to provide the
equals(Object obj)
andhashCode()
method implementation insuper
class
asJava
did. We all know that Java provide thehashCode() and equals(Object obj)
method implementation in the base class java.lang.Object, and when ever required weoverride
them in ourclass
.No, it's not possible to conform to the equals contract when introducing new fields which are relevant to the equals method. See "Effective Java" by Joshua Bloch for more information.
Edit:
I don't have the book at hand right now, but I think it's ok if the base class is abstract/ cannot be instantiated.
I think it is perfectly fine as long as you follow eqauls() and hashcode() contracts.
You could use the
super()
method to call the method of class that you're extending to prevent any need of code duplication