【问题标题】:How can I call a method of an outer class if my inner class implements something different than the outer class?如果我的内部类实现了与外部类不同的东西,我如何调用外部类的方法?
【发布时间】:2015-08-11 20:32:08
【问题描述】:

我的代码如下所示:

class A {
      void myMethod() {
      ...
      }

      class B implements class C {
      // ... how can I call myMethod here?
      }
}

如果我不够明确或我的问题有任何错误,我很抱歉。

【问题讨论】:

  • 我自己,我真的不知道你的问题是什么。您能否向我们展示真实代码并提供有关您的问题的更具体信息。
  • 内部类实例对其封闭实例具有隐式引用。可以直接使用myMethod();。
  • 我的回答有用吗?如果没有,请随时问我任何问题。如果是这样,请确保将其标记为最佳答案! :)

标签: java class methods nested


【解决方案1】:

你应该可以直接调用该方法:

class A {
  void myMethod() {
  ...
  }

  class B implements class C {
    public void init() {
      myMethod(); // calls myMethod() from A
    }
  }
}

在那种情况下B类也有一个名为“myMethod”的方法,那么请看这个问题:Calling outer class function from inner class

class A {
  void myMethod() {
  ...
  }

  class B implements class C {
    public void init() {
      // calls myMethod from A even tho myMethod is also defined on B
      A.this.myMethod();
    }

    void myMethod() {
    }
  }
}

我只能猜测这回答了你的问题,但很难说,因为你没有提供你遇到问题的实际代码。

【讨论】:

    【解决方案2】:

    使用它在不同的类中运行方法:

    class.method();
    

    这将运行类中的方法方法。

    如果你想调用的方法在你调用它的同一个类中,你可以只写方法名:

    method();
    

    【讨论】:

      猜你喜欢
      • 2013-04-26
      • 2019-04-16
      • 1970-01-01
      • 1970-01-01
      • 2014-08-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-08
      相关资源
      最近更新 更多