Java 8接口中静态方法的目的是什么? [英] What is the purpose of a static method in interface from Java 8?

查看:316
本文介绍了Java 8接口中静态方法的目的是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么Java 8支持静态方法?下面代码中main方法中两行的区别是什么?

Why are static methods supported from Java 8? What is the difference between the two lines in main method in below code?

package sample;
public class A {
    public static void doSomething()
    {
        System.out.println("Make A do something!");
    }
}

public interface I {
    public static void doSomething()
    {
        System.out.println("Make I do something!");
    }
}

public class B {
    public static void main(String[] args) {
        A.doSomething(); //difference between this
        I.doSomething(); //and this
    }
}

正如我们上面所看到的,我甚至没有在B中实现。当我们可以在另一个类中编写相同的静态方法并调用它时,在接口中使用静态方法的目的是什么?是否为模块化以外的任何其他目的引入。通过模块化,我的意思是:

As we can see above, I is not even implemented in B. What purpose would it serve to have a static method in an interface when we can write the same static method in another class and call it? Was it introduced for any other purpose than modularity. And by modularity, I mean the following:

public interface Singable {
    public void sing();
    public static String getDefaultScale()
    {
        return "A minor";
    }
}

只是将类似方法放在一起。

Just to put like methods together.

推荐答案

过去,如果你有一个接口 Foo 并想要分组界面 - 相关的utils或工厂方法,您需要创建一个单独的utils类 FooUtils 并将所有内容存储在那里。

In the past, if you had an interface Foo and wanted to group interface-related utils or factory methods, you would need to create a separate utils class FooUtils and store everything there.

这些类除了名称之外没有任何共同点,另外,需要将utils类设为 final 并有一个私有构造函数来禁止不必要的使用。

Those classes would not have anything in common other than the name, and additionally, the utils class would need to be made final and have a private constructor to forbid unwanted usage.

现在,由于接口静态方法,您可以将所有内容保存在一个位置而无需创建任何其他类。

Now, thanks to the interface static methods, you can keep everything in one place without creating any additional classes.

同样重要的是不要忘记所有良好实践,不要盲目地将所有内容抛给一个接口类 - 正如这个答案

It's also important to not forget all good practices and not throw everything mindlessly to one interface class - as pointed out in this answer

这篇关于Java 8接口中静态方法的目的是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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