So, I have an interface with a bunch of methods that need to be implemented, the method names are irrelevant.
The objects that implement this interface are often put into collections, and also have a special toString() format that I want them to use.
So, I thought it would be convenient to put hashCode(), equals(), and toString() into the interface, to make sure that I remember to override the default method for these. But when I added these methods to the interface, the IDE/Compiler doesn’t complain if I don’t have those three methods implemented, even though I explicitly put them in the interface.
Why won’t this get enforced for me? It complains if I don’t implement any of the other methods, but it doesn’t enforce those three. What gives? Any clues?
All objects in Java inherit from
java.lang.Objectand Object provides default implementations of those methods.If your interface contains other methods, Java will complain if you don’t implement the interface fully by providing an implementation of those methods. But in the case of
equals(),hashCode()andtoString()(as well as a few others that you didn’t mention) the implementation already exists.One way you might be able to accomplish what you want is by providing a different method in the interface, say,
toPrettyString()or something like that. Then you can call that method instead of the defaulttoString()method.