如何确保使用接口实现公共静态函数

0 java interface java-8

从Java 8开始,我们可以在接口中定义静态和默认方法.但我需要确保一个公共静态方法说foo()要在实现特定接口的所有类中实现interface A.我该怎么做,或者它是否可能?

界面A:

package com.practice.misc.interfacetest;

public interface A {
    public static Object foo(); //Eclipse shows error : 'This method requires a body instead of a semicolon'
    String normalFunc();
}
Run Code Online (Sandbox Code Playgroud)

B级:

package com.practice.misc.interfacetest;

public class B implements A{

    @Override
    public String normalFunc() {
        return "B.normalFunc";
    }
//I need to ensure that I have to define function foo() too

}
Run Code Online (Sandbox Code Playgroud)

C级:

package com.practice.misc.interfacetest;

public class C implements A{

    @Override
    public String normalFunc() {
        return "C.normalFunc";
    }
//I need to ensure that I have to define function foo() too

}
Run Code Online (Sandbox Code Playgroud)

编辑1:实际案例:

getInstance()在所有实现类中都有一个公共静态方法(返回该类的Singleton实例),我想确保其他开发人员编写的所有未来类必须在其类中实现该静态方法.我可以通过getInstance()从接口的静态方法调用方法来简单地使用反射来返回该实例,但我想确保每个人都getInstance()在所有实现类中实现.

Eug*_*ene 8

接口的静态方法不是继承的(1).它们是在类的情况下继承的,但是你不能覆盖它们(2); 因此,你想要做的事实上是不可能的.

如果您希望所有类都实现您的方法,为什么不简单地abstract(并且隐含地public)开始它,以便每个人都被迫实现它.