我很困惑为什么以下内容不被允许:
public interface MyInterface {
MyInterface getInstance(String name);
}
public class MyImplementation implements MyInterface {
public MyImplementation(String name) {
}
@Override
public static MyInterface getInstance(String name) { // static is not allowed here
return new MyImplementation(name)
}
}
我理解为什么接口中的方法不能是静态的,但为什么覆盖该方法的方法不能是静态的呢?
我希望所有类都实现
getInstance(String name)
方法,但目前只能在已经实例化对象的情况下调用该方法,这有点违背初衷...更新:谢谢回答,我现在更好地理解了。基本上我不应该试图让一个实用类(或工厂类)实现一个接口(或至少不是这种方式)...
MyImplementation.getInstance("foo");
而不是new MyInterface("foo").getInstance("foo");
。 - KidTempo