Search code examples
javacloneabstract-classequalshashcode

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.


Solution

  • 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.