Everyone using Java is aware of the fact that you can declare abstract methods in your superclasses and each subclass needs to implement this method (for sure if the class is not abstract itself). But did you know that you can go the other way round and overwrite an already defined method with an abstract one? And what would that be useful for? Let’s take an easy to understand example here:

Object defines the method toString which only prints by default the class name along with the hash code. The following code snippet is taken from the latest Oracle Java 7 implementation.

I hope everyone agrees that at least for entities, DTOs and every kind of data bean you should overwrite this method. Otherwise, your log will be filled with information which you can barely read and debugging your application makes it just too hard. So the solution is easy: let every developer take care of overwriting this method if they are going to create a new class. Problem solved? Yes and no. From my experience, there are always cases where you just forget to overwrite this method. Thus it wouldn’t be too bad to “force” all the developers to never forget to overwrite this method. For this, you can do the following: Create some kind of abstract class in between and define toString again as abstract:

Even though at first sight you might think that this approach would not work and Java would throw an error, but actually it really does work! The only thing that you need to take care of now is for every Pojo to extend this class and you would immediately be notified to overwrite this method.

And toString is only the beginning. equals and hashCode are methods which are often forgotten to be implemented but are very important for some operations. Even though hashCode is being defined as native in the Object class, you can use the same approach here and go with the following definition:

In total, these are only small changes which can have a great effect in debugging your application. And as there is often the case that you already have some kind of superclass for your entities, DTOs etc. you can easily add these definitions and let your preferred IDE remind you to never forget to overwrite these methods again.

— Patrice

Leave a Comment

4 comments

  1. M

    A useful tipp of the day. Never thought about this.

    Mike

  2. b

    Thank You

  3. B

    Thank you for that post, Danke, Merci

    Regards

    Bouhedli Mohamed Nassim

  4. S

    Thank you for this unique post..

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close