Search code examples
javainheritancefluent-interface

How to reuse common extended Interface method in Java?


I have these three Interfaces as part of the Fluent Interface API (where a lot of method chaining happens):

    interface VerifierA extends VerifierC {

      VerifierA method1();
      // other methods elided
    }

    interface VerifierB extends VerifierC {
     VerifierB method1();
       // other methods elided
    }

   interface VerifierC {
   VerifierA commonMethod();
   }

By declaring commonMethod() as VerifierA I can then chain methods commonMethod().method1() but not commonMethod().method2();

How can I have commonMethod() in VerifierC return to both VerifierA or VerifierB as needed?


Solution

  • you could solve it with generics:

    interface VerifierA extends VerifierC<VerifierA> {
         VerifierC<VerifierA> method1();
    }
    
    interface VerifierB extends VerifierC<VerifierB> {
        VerifierC<VerifierB> method1();
    }
    
    interface VerifierC<T> {    
        T commonMethod();
    }