从 Java 8 开始,我们可以在接口(interface)中定义静态方法和默认方法。但我需要确保在实现特定接口(interface)(例如interface A
)的所有类中实现一个公共(public)静态方法(例如foo()
)。我该如何做到这一点,或者这是否可能?
接口(interface)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();
}
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
}
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
}
编辑1: 实际案例:
我在所有实现类中都有一个公共(public)静态方法 getInstance()
(返回该类的 Singleton 实例),并且我想确保其他开发人员将来编写的所有类都必须具有该静态方法在他们的类里面实现。我可以简单地使用反射通过从接口(interface)的静态方法调用 getInstance()
方法来返回该实例,但我想确保每个人都实现 getInstance()
> 在所有实现类中。
最佳答案
接口(interface)中的静态方法不能继承(1)。如果是类,它们是继承的,但不能覆盖它们 (2);因此你想要做的事情实际上是不可能的。
如果您希望所有类都实现您的方法,为什么不简单地使其抽象
(并且隐式public
)开始,以便每个人都被迫来实现它。
关于java - 如何确保使用接口(interface)实现公共(public)静态函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49637472/