[英]Java - For a given function foo(X i); in Interface X, why can't implementing class Y change it to foo(Y i)?
For example 例如
public interface X{
public void foo(X i);
}
public class Y implements X{//error: doesn't implement foo(X i)...
public void foo(Y i){
fooBar(foo);
}
....
}
Why can't I do that?
我为什么不能这样做?
And how can I change it so this is possible?
我该如何更改呢?
What can I do to declare foo in X with a parameter, and then be able to use Y as the parameter type in Y? 我该怎么做才能在X中使用参数声明foo,然后可以将Y用作Y中的参数类型?
By changing the type of the input parameter in class Y, you have changed the signature of the method which means the compiler sees it as a completely different method. 通过更改类Y中的输入参数的类型,可以更改方法的签名,这意味着编译器将其视为完全不同的方法。
A Java interface is like a contract. Java接口就像合同。 Anything implementing it must implement the exact methods it defines.
任何实现它的方法都必须实现它定义的确切方法。 By using a different method signature you are not really implementing the defined method and so you are breaking that contract.
通过使用不同的方法签名,您实际上并没有实现已定义的方法,因此您正在违反该合同。
Additionally to what Don Boyle said, you can't change it without hinting the compiler of the intention. 除了Don Boyle所说的之外,您不能在不暗示编译器意图的情况下对其进行更改。 You do this by introducing Generics to the interface, like so:
您可以通过向接口引入泛型来实现此目的,如下所示:
public interface X<T> {
public void foo(T i);
}
public class Y implements X<Y> {
public void foo(Y i){
fooBar(foo);
}
}
Try something like 尝试类似
interface X<T extends X> {
public void foo(T a);
}
class Y implements X<Y> {
public void foo(Y a);
}
Suppose you had done as you want, and suppose Java allowed it. 假设您已按需完成,并假设Java允许。 And let's say another class - call it Z - also implements X. Because Z implements X, and because of the definition of X, you must be able to call X.foo(z) for any Z z.
假设另一个类-称为Z-也实现X。由于Z实现X,并且由于X的定义,您必须能够为任何Z z调用X.foo(z)。 But Y, which is an X, doesn't know what to do if you pass a Z to its foo().
但是Y(它是X)不知道将Z传递给它的foo()时该怎么办。 That's why.
这就是为什么。
通过实现接口X,您可以保证在该接口上实现所有方法,这意味着foo方法可以采用任意X。现在,如果仅接受Ys作为foo方法的参数,则不会完全实现接口,因为其他所有实现X的类都不是foo的有效参数。
Because Interface specifies common behavior for all implementing classes. 因为Interface为所有实现类指定了通用行为。 Let's say you'd have some other classes all implementing X you would expect that if you have object of class X you can call foo with parameter that is of class X (which can be any of it's subclasses or implementations) so let's say you'd have code like this:
假设您还有其他一些都实现X的类,那么您会期望,如果您拥有类X的对象,则可以使用类X(可以是其子类或实现中的任何一个)的参数来调用foo,那么假设您是d具有如下代码:
class Z implements X {
...
}
Z z = new Z();
X x = new Y();
x.foo(z);
Which would be false since with your code foo would only accept arguments of class Y 这将是错误的,因为使用您的代码foo将仅接受类Y的参数
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.