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).
toString()
Can this be achieved? Declaration public abstract String toString(); with or without @Override annotation in the interface enclosure is legal, but has no effect.
public abstract String toString();
@Override
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
Yup, sort of.
protected abstract String internToString();
and then
@Override public String toString() { return internToString(); }
in the base class.
I think you do not need to declare anything other than implementing the toString() method in a specific class.
If you create an abstract class, you do not need another method:
abstract
public abstract class Base{ public abstract String toString(); } ... public class Sub extends Base{} //will not compile