Home > Net >  how to add common statements to all the implementations of an interface?
how to add common statements to all the implementations of an interface?

Time:03-11

I have a code in this current form.

public interface Converter {
    void convert();
}

public class X implements Converter{
   public void convert(){
      System.out.println("X conversion");
  }
}

public class Y implements Converter{
   public void convert(){
      System.out.println("Y conversion");
  }
}

Now I need to add common steps in all the implementations of convert() method. Like System.out.println("common steps") to all the implemenations of convert() method. What is the best way to do

CodePudding user response:

Steps to achieve it:

  1. Make abstract class implementing Converter, with its' implementation of convert() holding common logic
  2. Add abstract method, which will hold logic specific for concrete implementers, X and Y in your case
  3. Call abstract method in convert()
  4. Make X and Y extend abstract class
  5. Implement specific logic

CodePudding user response:

You can do this by using default method of interface. Default method in interface must have function body. You can use it this way.

public interface Converter {
    default void convert(){
      System.out.println("common steps");
    }
}

public class X implements Converter{
   public void convert(){
      Converter.super.convert();
  }
}

public class Y implements Converter{
   public void convert(){
      Converter.super.convert();
  }
}
  •  Tags:  
  • java
  • Related