Java通用接口方法的实现 [英] Common interface method implementation in java

查看:69
本文介绍了Java通用接口方法的实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个实现特定接口的类.
我想实现一个将由2个类共享的方法.
我可以将该方法实现添加到接口类中,然后从2个类中对该方法进行调用吗?

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?

例如:

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?

推荐答案

是的,如果您使用的是Java 8,则可以创建 default 实现,如下所示:

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

有关更多信息,请参见有关此功能的Oracle文档

如果您能够对代码进行更广泛的更改,则可以使用的另一种策略是使用抽象类而不是接口,并使实现类 extend该类.界面中任何您不想为其编写默认值的方法都应标记为抽象.

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

这篇关于Java通用接口方法的实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆