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:
- Make abstract class implementing
Converter
, with its' implementation ofconvert()
holding common logic - Add abstract method, which will hold logic specific for concrete implementers,
X
andY
in your case - Call abstract method in
convert()
- Make
X
andY
extend abstract class - 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();
}
}