java 如何在实现接口的类中实现静态方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17970364/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-01 19:44:22  来源:igfitidea点击:

how to implement a static method in a class that implements an interface?

javastatic-methodsinterface-implementation

提问by idell

I'm implementing a java class that implements an interface.
The poi is that, a method in this class must be static, but in the interface I can't (as known) declare a method as static, and if I try to declare it in the class, I get this error: "This static method cannot hide the instance method from InterfaceName".

我正在实现一个实现接口的 java 类。
问题是,此类中的方法必须是静态的,但在接口中我不能(众所周知)将方法声明为静态,如果我尝试在类中声明它,我会收到此错误:“这静态方法无法从 InterfaceName 隐藏实例方法”。

I've searched in this site but I haven't found any solution but a suggestion said to create an abstract class that implements the interface, and then extend the abstract one in the class, but it doesn't work.

我在这个网站上搜索过,但我没有找到任何解决方案,但建议创建一个实现接口的抽象类,然后在类中扩展抽象类,但它不起作用。

Any suggestion?

有什么建议吗?

Thanks a lot to everybody!

非常感谢大家!

回答by Icermann

The link mvw posted ( Why can't I define a static method in a Java interface?) describes the reason for not allowing static methods in interfaces and why overriding static methods iis not a good idea (and thus not allowed).

mvw 发布的链接(为什么我不能在 Java 接口中定义静态方法?)描述了不允许在接口中使用静态方法的原因以及为什么覆盖静态方法不是一个好主意(因此不允许)。

It would be helpful to know in what situation you want to use the static method. If you just want to call a static method of the class, jut give it another name as andy256 suggested. If you want to call it from an object with a reference to the interface, do you really need the method to be static?

知道在什么情况下要使用静态方法会很有帮助。如果您只想调用类的静态方法,只需像 andy256 建议的那样给它另一个名称。如果你想从一个引用接口的对象调用它,你真的需要这个方法是静态的吗?

To get around the problem, my suggestion is that if you really want to call a static method with the same signature as the interface method, call a private static method:

为了解决这个问题,我的建议是,如果你真的想调用一个与接口方法具有相同签名的静态方法,调用一个私有的静态方法:

class MyClass implememts SomeInterface {

    @Override
    public int someMethod(int arg1, int arg2) {
        return staticMethod(arg1, arg2);
    }

    private static int staticMethod(int arg1, int arg2) {
        // TODO: do some useful stuff...
        return arg1 + arg2;
    }
}