简体   繁体   English

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

[英]Confused about Interfaces. How do I call an interface method in one class and define it in another?

I'm new to interfaces and I'm trying to do the following. 我是界面的新手,我正在尝试执行以下操作。 What am I missing? 我想念什么?

public class MyAdapter implements ItemManager.DoThisInterface {
    ...
    @Override
    doThis() {
        // Do things specific to my adapter. Define action hre.
    }
}

The interface is defined in the Item Manager, which does not know what needs to be done. 该接口在“项目管理器”中定义,该管理器不知道需要做什么。 The adapter should define the actions. 适配器应定义操作。

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();
    }
}

You may need to create an object. 您可能需要创建一个对象。

MyAdapter ma=new MyAdapter();
ma.doThis();

Call this and your problem will be solved. 打电话给您,您的问题将得到解决。

You should set a DoThisInterface instance on the class ItemManager , and save it in the instance field, then use the instance to call the interface method, like this 你应该设置一个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-2023 STACKOOM.COM