Make each inheritance chain class override the abstract method

Suppose I have an inheritance chain where each class extends its superclass by adding a new field, and I want each class in this chain to override the method toString()as follows:

public String toString()
{
    return super.toString() + "[newfield=" + newfield + "]";
}

If I use an abstract base class, then when the class of the inheritance chain becomes concrete, implementing the abstract method, all subclasses from this point become concrete, inheriting the already implemented method.

Is there a way in Java to force each class to override (override) an abstract method, even if it is already implemented above in the inheritance chain?

+3
source share
2 answers

The short answer is no.

: unit test, ( ​​, reflections), . .

Java, AspectJ pointcut hasMethod(), , , , declare parents. , , aspectj:

  • IllBehaved.
  • , , ,
  • ,

    pointcut isSubTypeOfYourClass(): within(com.your.BaseClass+);
    pointcut overridesMethod(): hasmethod(public void yourMethodName(..));
    declare parents: isSubTypeOfYourClass() && !overridesMethod()
                     implements com.yourcompany.IllBehaved;
    declare error: isSubTypeOfYourClass() && within(com.yourcompany.IllBehaved+):
                     "Implementation class must override <Foo> method";
    

, , -XhasMember. aspectj , , Maven, Ant, Eclipse ..

+3

, . , , , .

+2

All Articles