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