I have 2 classes that implements a particular interface.
I would like to implement a method that would be shared by the 2 classes.
Can I add that method implementation to the interface class and then make a call to that method from the 2 classes?
For eg:
public interface DM
{
public static void doSomething() {
System.out.println("Hello World");}
}
public class A implements DM
{
doSomething();
}
public class B implements DM
{
doSomething();
}
}
Is this feasible?
What is the proper way to do this?
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");
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With