从外部类引用内部类中的方法

时间:2015-08-03 11:48:22

标签: java class inner-classes

我有以下代码,尽管类和memeber方法是公开的,我无法在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++}
    }
}

2 个答案:

答案 0 :(得分: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));
    }
}

答案 1 :(得分:0)

您需要以

的形式访问它 HF hF = this.new HF();   hF.methodHF()

相关问题