[英]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.