How to ensure that the toString () method is overridden in a class?

Suppose I have an interface and many classes that implement this interface. I want to provide an override of the default implementation of toString() in each of these classes (that is, if some classes do not override it, this should lead to a compilation error).

Can this be achieved? Declaration public abstract String toString(); with or without @Override annotation in the interface enclosure is legal, but has no effect.

+7
source share
4 answers

Write an annotation and annotation handler and use it at compile time.

Your annotation will look like this:

 public @ interface MustOverrideToString { } 

and your annotation handler will look for any class that

  • extends class using MustOverrideToString annotation
  • does not override toString
+2
source

Yup, sort of.

 protected abstract String internToString(); 

and then

 @Override public String toString() { return internToString(); } 

in the base class.

+14
source

I think you do not need to declare anything other than implementing the toString() method in a specific class.

+1
source

If you create an abstract class, you do not need another method:

 public abstract class Base{ public abstract String toString(); } ... public class Sub extends Base{} //will not compile 
0
source

All Articles