Suppose I have an inheritance chain where every class extends its superclass by adding a new field and I want every class of that chain to override the toString() method like so:
public String toString()
{
return super.toString() + "[newfield=" + newfield + "]";
}
If I use an abstract base class then when a class of the inheritance chain becomes concrete by implementing the abstract method all the subclasses from that point on become concrete as well by inheriting the already implemented method.
Is there a way in Java to force every class to override (reimplement) the abstract method even though it has already been implemented higher in the inheritance chain?
Short answer: no.
Long answer: you could write a unit test that scans the class path (use a library like reflections for that), loads every subclass of the abstract class and checks for the method using reflection. But there’s no way to do it at compile time.
Aside from Java,
AspectJ has a
hasMethod()pointcut, which could do the check for you, but unfortunately that’s only valid for thedeclare parentsadvice. Perhaps you could do it in two steps using aspectj:IllBehaved.then declare a compile error for all types that implement this interface
I haven’t tested this, but it should work if you turn on the
-XhasMemberoption.And it’s easy enough to integrate aspectj into your build when you use standard tools like Maven, Ant, Eclipse etc.