Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Common interface method implementation in java

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?

like image 769
Shenoy Tinny Avatar asked Nov 17 '15 17:11

Shenoy Tinny


2 Answers

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();
}
like image 122
Rosa Avatar answered Sep 20 '22 00:09

Rosa


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");
    }

}
like image 34
Ákos Ratku Avatar answered Sep 22 '22 00:09

Ákos Ratku