[英]Confused about Interfaces. How do I call an interface method in one class and define it in another?
我是界面的新手,我正在嘗試執行以下操作。 我想念什么?
public class MyAdapter implements ItemManager.DoThisInterface {
...
@Override
doThis() {
// Do things specific to my adapter. Define action hre.
}
}
該接口在“項目管理器”中定義,該管理器不知道需要做什么。 適配器應定義操作。
public class ItemManager {
....
private void onCertainEvent() {
doThis(); // do whatever is overriden in adapter.
// this is kind of a placeholder for what i expect to be defined
// in the adapter.
// (this fails to compile because it can't call straight to the interface method)
}
// interface declaration
public interface DoThisInterface {
doThis();
}
}
您可能需要創建一個對象。
MyAdapter ma=new MyAdapter();
ma.doThis();
打電話給您,您的問題將得到解決。
你應該設置一個DoThisInterface
的類實例ItemManager
,並將其保存在實例字段,然后使用該實例調用接口方法,這樣
public class ItemManager {
private DoThisInterface mDoThisInterface;
....
private void onCertainEvent() {
if(mDoThisInterface != null){
mDoThisInterface.doThis();
}
}
public void setDoThisInterface(DoThisInterface doThisInterface){
mDoThisInterface = doThisInterface;
}
// interface declaration
public interface DoThisInterface {
doThis();
}
}
問題未解決?試試以下方法:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.