java - 为什么Java接口(interface)不能通过不太具体的功能来实现

标签 java oop interface

为什么我不能在 Java 中这样做:

interface Context{
    void add(Integer o);
}
class Subclass implements Context{
    @Override
    public void add(Object o){...}
}

难道 Subclass.add 不会已经实现了 Context.add,因为它 add(Object) 可以执行 add(Integer) 可以执行的所有操作吗?

解决这个问题的好方法是什么?

现在我正在做一种丑陋的方式:

private void actuallyAdd(Object o){...}
public void add(Object o){actuallyAdd(o);}
public void add(Integer o){actuallyAdd(o);}

编辑:这不是上述问题的重复。在给定的问题中,父类(super class)是具有更通用的“对象”作为参数的父类(super class),而子类则更具体。这不起作用,因为更具体的方法可能无法处理任何对象。在我的问题中,子类不如父类(super class)具体,这意味着子类始终能够处理父类(super class)需要的任何内容。

最佳答案

这是因为 Java 编译器要求覆盖方法的签名是被覆盖方法的“子签名”。即要么参数类型相同,要么参数类型删除相同。

JLS, Section 8.4.8.1 , 说明如下:

An instance method mC declared in or inherited by class C, overrides from C another method mI declared in interface I, iff all of the following are true:

...

  • The signature of mC is a subsignature (§8.4.2) of the signature of mI.

Section 8.4.2 :

The signature of a method m1 is a subsignature of the signature of a method m2 if either:

  • m2 has the same signature as m1, or

  • the signature of m1 is the same as the erasure (§4.6) of the signature of m2.

您可以通过声明一个泛型类型参数来解决这个问题,正如另一个答案所指出的,尽管尚不清楚接口(interface)的最初目的是采用 Integer 还是只是一些特定但未知的类型.

关于java - 为什么Java接口(interface)不能通过不太具体的功能来实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50710444/

相关文章:

java - Android 7.1.1 SSLHandShakeException 连接被对端关闭

design-patterns - 更新多个实体的方法通常不是 DAO 的一部分吗?

java - 是 M :N a bad style in OOP? 有没有更好的办法来管理 m :n relationships?

ios - Swift 协议(protocol)中的可选闭包

delphi - 在Delphi中实现接口(interface)时,实现方法不在public部分有关系吗?

java - 如果另一个类中的方法不是静态的,为什么我无法获取该方法的返回值?

java - 省略 for 循环中的第一个参数

java - Json-Jersey 无法解码参数化根列表

java - 提取tar文件时如何检测文件权限?

C#:表示方法的可执行方式作为接口(interface)的一部分存在