Andrejs
Andrejs

Reputation: 11961

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?

Upvotes: 1

Views: 116

Answers (1)

Daij-Djan
Daij-Djan

Reputation: 50109

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();
}

Upvotes: 2

Related Questions