繁体   English   中英

对接口感到困惑。 如何在一个类中调用接口方法并在另一个类中定义接口方法?

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM