mercredi 13 janvier 2021

Java Interface : Use default method implementation in implementation classes

I have an interface and its 2 or more implementations say,

public interface IProcessor {
  default void method1() {
   //logic
  }
  default void method2() {
   //logic
  }
  public void method3();
  public void method4();
}

Here, The method1 and method2 implementation logic is common across all multiple multiple implementation classes. So defined as default methods. So only the rest of methods can be override in the implementation classes.

public CarImpl implements IProcessor {
@override 
public void method3(){
//logic
}
@override 
public void method4(){
//logic
}
}

public VanImpl implements IProcessor {
@override 
public void method3(){
//logic
}
@override 
public void method4(){
//logic
}
}

Is there a better approach that I can achieve this with out default methods and with out redundant code in the respective implementation classes. Because if the code in the default methods increases then the interface looks clumsy.

Aucun commentaire:

Enregistrer un commentaire