【问题标题】:referencing method in the inner class from the outer class从外部类引用内部类中的方法
【发布时间】:2015-08-03 11:48:21
【问题描述】:

我有以下代码,尽管类和成员方法是公开的,但我无法在 methodLMF 中引用 methodHF 而不是 methodBF。我尝试了以下方法:

LMF.this.xxxx //but the methods do not show up

请告诉我如何解决它。

代码

class LMF {
    LMF() {}

    public methodLMF() { } // should return methodHF+methodBF

    //class HF
    class HF {
        HF() {}

        public methodHF(int x) {x++}
    }

    //class BF
    class BF {
        BF() {}

        public methodBF(int x) {x++}
    }
}

【问题讨论】:

  • 请输入实际可验证的代码。不仅仅是骨架。
  • 这些是实例方法,所以只有当你有一个HF的instance和一个BF的instance时才能引用它们。

标签: java class inner-classes


【解决方案1】:

您需要创建 HF 和 BF 的对象才能访问那里的方法。

class LMF {
    LMF() {
    }

    public int methodLMF(int x) {
        return new HF().methodHF(x) + new BF().methodBF(x);
    } // should return methodHF+methodBF

    // class HF
    class HF {
        HF() {
        }

        public int methodHF(int x) {
            return x++;
        }
    }

    // class BF
    class BF {
        BF() {
        }

        public int methodBF(int x) {
            return x++;
        }
    }

    public static void main(String[] args) {
        System.out.println(new LMF().methodLMF(1));
    }
}

【讨论】:

    【解决方案2】:

    你需要访问它

    HF hF = this.new HF(); hF.methodHF()

    【讨论】:

      猜你喜欢
      • 2014-08-28
      • 1970-01-01
      • 2023-03-23
      • 2019-04-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多