'how to add common statements to all the implementations of an interface?
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
Solution 1:[1]
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,
XandYin your case - Call abstract method in
convert() - Make
XandYextend abstract class - Implement specific logic
Edit: Adding example code to illustrate it.
Abstract class:
public abstract class BaseConverter implements Converter {
@Override
public void convert() {
System.out.println("common steps");
this.specificSteps();
}
protected abstract void specificSteps();
}
Implementation of convert() consists of common part - System.out.println("common steps");, and specific part - this.specificSteps();. Abstract method specificSteps() forces every subclass to add its' own specific conversion.
X and Y:
public class X extends BaseConverter {
@Override
protected void specificSteps() {
System.out.println("X conversion");
}
}
public class Y extends BaseConverter {
@Override
protected void specificSteps() {
System.out.println("Y conversion");
}
}
Like this you only write the specific logic in concrete classes, they inherit common logic from BaseConverter.
Lastly, simple main to test.
public class TempMain {
public static void main(String[] args) {
List<Converter> converters = new ArrayList<>();
converters.add(new X());
converters.add(new Y());
for (Converter converter : converters) {
converter.convert();
System.out.println();
}
}
}
Solution 2:[2]
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();
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Deep |
