I am a tutor for Java programming. My students are currently forced (not by me, but by an unclear assignment) to implement clone(), equals() and hashCode() for an abstract class.
Does it make sense to implement clone(), equals() or hashCode() for an abstract class? Could you give an example where this makes sense?
I could imagine that it makes sense when you have some subclasses x, y, z of an abstract class a. Those subclasses might only differ in the implementation of a method, so you don't need to implement those three methods three times. But I can't imagine any situation where this could be the case.
I wouldn't implement clone()
.
But it makes sense to implement equals()
, hashCode()
, and toString()
to provide the default behavior for all subclasses. Children can choose to use it if they add no new class members or supplement as needed.
misread your question and thought you also asked about toString
- same reasoning applies anyway
For example, AbstractCollection
implements toString()
which basically iterates over the collection and prints it in a user-friendly way.
Direct Subclasses:
AbstractList, AbstractQueue, AbstractSet, ArrayDeque, ConcurrentLinkedDeque
So all sets, lists and queues share that toString
method. Each subclass is free to reimplement it if required.
As another example, equals
is implemented one level lower (in AbstracList/Set etc.).
On the other hand, clone
is implemented in the final implementation (ArrayList for example), but not in the abstract classes.
Bottom line: sometimes it makes sense but sometimes it doesn't and it should probably not be an obligation applied to all circumstances.
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