【问题标题】:Calling another classes method with the object of the class使用类的对象调用另一个类方法
【发布时间】:2013-04-21 07:47:02
【问题描述】:

A 实现接口I 需要方法doAction()。如果我从类A ofB 调用一个方法,并将“this”(类A)传递给该方法,我怎么能调用一个存在于类中的方法A 来自 B 类中的方法?例如:

class A implements I {
    public void start() {
        B.myMethod(this);
    }

    @Override
    public void doAction() {
        // Do stuff...
    }
}

Class B {
    public void myMehtod(Class theClass) { //How would I accept 'this', and...
        theClass.doAction(); //How would I call the method?
    }
}

我这样做是为了自定义库,但不知道扩展 I 的类的确切名称。

【问题讨论】:

  • 您在“myMehtod”中有错字
  • 根据您的最终目标,您可能会发现阅读Command Pattern 很有帮助。

标签: java methods interface this implementation


【解决方案1】:

这是一个关于接口如何工作的非常基本的问题。我建议尝试找到有关它们的教程。

无论如何,您所要做的就是声明一个以接口为类型的参数。您可以在接口类型(或实现该接口的任何子接口或类)的变量上调用接口方法。

Class B {
    public void myMethod(I theClass) {
        theClass.doAction();
    }
}

【讨论】:

    猜你喜欢
    • 2014-07-19
    • 2015-06-16
    • 1970-01-01
    • 2013-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-12
    • 1970-01-01
    相关资源
    最近更新 更多