Why can't implementing classes define an overriding method as static?

后端 未结 4 916
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-17 05:56

I\'m confused why the following is not allowed:

public interface MyInterface {
  MyInterface getInstance(String name);
}

public class MyImplementation imple         


        
4条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-17 06:31

    Invoking static methods in Java requires you to specify the exact type. It is not possible to invoke static methods polymorphically, eliminating the need for @Override.

    Please note that this approach is not universal across all languages: for example, you can override class methods in Objective-C, and Apple's cocoa frameworks make good use of this mechanism to customize their "factory" classes. However, in Java, C++, and C# class methods do not support polymorphic behavior.

    Theoretically, Java designers could have let you provide interface method implementations through static methods in case an implementation does not need to access the state from the instance. But the same behavior is simple to achieve with a trivial wrapper:

    public class MyImplementation implements MyInterface {
        public MyImplementation(String name) {
        }
        @Override
        public MyInterface getInstance() { // static is not allowed here
            return getInstanceImpl();
        }
        public static getInstanceImpl() {
            return new MyImplementation(name)
        }
    }
    

    Java compiler could have done the same thing on your behalf, but seeing a static method implement an instance method is both unusual and confusing, so my guess is that Java designers decided against providing this "piece of magic".

提交回复
热议问题