Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does it make sense to implement clone(), equals() or hashCode() for an abstract class?

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.

like image 333
Martin Thoma Avatar asked Jan 07 '13 17:01

Martin Thoma


2 Answers

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.

like image 76
duffymo Avatar answered Oct 18 '22 06:10

duffymo


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.

like image 40
assylias Avatar answered Oct 18 '22 07:10

assylias