[英]Can i use reference of implementing class into method declared in Interface in java
[英]Why can't I use an implementing class as an argument in another interface if the first interface defines it?
我有两个接口。 首先:
public interface IGoable {
int go();
}
第二个在它的方法定义中使用第一个接口作为参数类型:
public interface IMove {
int move(IGoable goThisMany);
}
我有一个实现IGoable接口的类:
public class ImplGoable implements IGoable {
@Override
public int go() {
return 0;
}
public int dumby() {
return 1;
}
}
这是问题所在。 我在一个类中实现了IMove接口,并尝试在实现的move()方法中使用ImplGoable类作为参数,如下所示:
public class TestGoThere implements IMove {
@Override
public int move(ImplGoable goImp) {
return goImp.go();
}
}
它给了我以下错误:
TestGoThere类型的方法move(ImplGoable)必须覆盖或实现超类型方法
为了避免这个错误,我必须使用IGoable接口作为实现方法中参数的类型,如下所示:
public class TestGoThere implements IMove {
@Override
public int move(IGoable goImp) {
return goImp.go();
}
}
为什么我无法使用ImplGoable类,因为它实现了IGoable接口?
您无法使用ImplGoable
IGoable
因为在您的声明中,您仅与IGoable
接口建立了合同。 ImplGoable
将实现并覆盖接口方法,但是没有阻止它添加新方法。 由于你的契约,你可以使用的方法是在你的接口中定义的方法,即go()
。因此你可以使用goImp
对象,但是在它的契约范围内只是这意味着对象可以是实现接口但是类型的任何有效对象需要只能进行IGoable
您可以使用泛型来解决这个问题(尽管您是否希望完全依赖于您的用例)。
如果您将界面IMove的定义更改为:
public interface IMove<T extends IGoable> {
int move(T goThisMany);
}
然后,这允许您在实现接口的类中定义具体实现,即:
public class TestGoThere implements IMove<ImplGoable> {
@Override
public int move(ImplGoable goImp) {
return goImp.go();
}
}
并允许您使用ImplGoable作为参数参数类型。 正如我所说,无论你是否愿意这样做都是完全不同的事情,而且取决于你想要做什么。 关于泛型, 这里有一些很好的阅读。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.