为什么实现类不能将覆盖方法定义为静态? [英] Why can't implementing classes define an overriding method as static?

查看:345
本文介绍了为什么实现类不能将覆盖方法定义为静态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很困惑为什么不允许以下内容:

I'm confused why the following is not allowed:

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)
  }
}

我明白为什么接口中的方法不能是静态的,但为什么不能覆盖这个方法呢?

I understand why a method in the interface cannot be static, but why can't the overriding method be?

我希望所有类都实现 getInstance(String name)方法,但我目前仅限于如果对象已经被实例化,那么能够调用该方法哪种方法会失败...

I want all classes to implement the getInstance(String name) method, but I'm currently limited to only being able to call the method if the object has already been instantiated which kind of defeats the purpose...

*更新: * 感谢您的回答,我现在明白了。基本上我不应该试图使实用程序类(或工厂类)实现一个接口(或至少,不是这样)...

*update:* Thanks for the answers, I understand it better now. Basically I shouldn't be trying to make a utility class (or a factory class for that matter) implement an interface (or at least, not in this way)...

推荐答案

在Java中调用静态方法需要您指定确切的类型。无法以多态方式调用静态方法,无需 @Override

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.

请注意这种方法并非在所有语言中都是通用的:例如,您可以在Objective-C中覆盖类方法,Apple的cocoa框架可以很好地利用这种机制来自定义它们的工厂类。但是,在Java,C ++和C#类方法中不支持多态行为。

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.

从理论上讲,Java设计人员可以让你通过 static 方法,以防实现不需要从实例访问状态。但是使用一个简单的包装器可以很容易地实现相同的行为:

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编译器可能代表你做了同样的事情,但是看到一个静态方法实现一个实例方法既不寻常又令人困惑,所以我的猜测是Java设计师决定反对提供这个魔法片。

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".

这篇关于为什么实现类不能将覆盖方法定义为静态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆