Common interface method implementation in java
Yes, if you are using Java 8, you can create a default
implementation, like this:
public interface DM
{
default void doSomething() { System.out.println("Hello World");}
}
or, if it should be static:
public interface DM
{
static void doSomething() { System.out.println("Hello World");}
}
For more information, see Oracle's documentation on the feature
Another strategy you could use, if you are able to make more widespread changes to your code, would be to use an abstract class
instead of an interface, and have your implementing classes extend
that class instead. Any methods in your interface that you do not want to write defaults for should be marked as abstract
.
public abstract class DM
{
public void doSomething() { System.out.println("Hello World");}
public abstract void doSomethingElse();
}
public class A extends DM
{
doSomething();
}
You could also combine the approaches if you want to use interfaces but can't/won't use defaults:
public abstract class DMImpl impelements DM
{
@Override
public void doSomething() { System.out.println("Hello World");}
}
public class A extends DM
{
doSomething();
}
You can create a default
method with Java 8. It has some limitations but good for some commonly shared functionality.
https://docs.oracle.com/javase/tutorial/java/IandI/defaultmethods.html
interface DM {
default public void doSomething() {
System.out.println("Hi");
}
}