为什么我可以重写静态接口方法?

huangapple go评论80阅读模式
英文:

Why can I override a static interface method?

问题

我找不到任何好的来源来解释为什么

```java
abstract class AA {
    public static void log() {}
}

class BB extends AA {
    public void log() {} //错误
}
interface CC {
    public static void log() {}
}

class DD implements CC {
    public void log() {} //可以
}
英文:

I can't find any good source explaining why:

abstract class AA {
    public static void log() {}
}

class BB extends AA {
    public void log() {} //error
}
interface CC {
    public static void log() {}
}

class DD implements CC {
    public void log() {} //Ok
}

答案1

得分: 9

如果子类定义了一个与父类中另一个静态方法具有相同签名的静态方法,则子类中的方法会隐藏超类中的方法。这与覆盖实例方法有两种不同之处:

  • 当你覆盖实例方法并调用它时,你会调用子类中的方法。
  • 当你对静态方法进行相同操作时,被调用的版本取决于从哪个类调用它。

至于接口,接口中的静态方法不会被继承。因此,从技术上讲,这不是一种覆盖。在你的示例中,你可以从类DD调用log(),或者你可以从接口CC调用log()(在这种情况下,你需要使用接口的名称来调用它:CC.log())。它们是不同的方法。

这个链接 是关于覆盖方法的良好资源,涵盖了类中的静态方法和实例方法,以及接口中的静态方法。

英文:

If a subclass defines a static method with the same signature as another static method in its parent class, then the method in the subclass hides the one in the superclass. This is distinct from overriding an instance method in two ways:

  • When you override an instance method and invoke it, you invoke the one in the subclass.
  • When you do the same for a static method, the invoked version depends on from which class you invoke it.

As for interfaces, static methods in interfaces are not inherited. Therefore it's technically not an override. In your example, you could call log() from class DD, or you could call log() from interface CC (in which case you'd need to call it using the name of the interface: CC.log()). They are separate methods.

This is a good resource on overriding methods that covers both static and instance methods in classes, and static methods in interfaces.

huangapple
  • 本文由 发表于 2020年9月13日 16:50:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/63868869.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定