为什么我不能在 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.
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/