Java: reference outer class in nested static class [duplicate]

蹲街弑〆低调 提交于 2020-01-23 19:26:49

问题


I have a class structure like this:

public class OuterClass {

    private static class InnerClass {

        public void someMethod() {
            OtherClass.otherMethod(<???>);
        }

}

which refers to a static method of some other class OtherClass:

public class OtherClass {

    public static void otherMethod(OuterClass) {
        ....
    }

}

I am trying to figure out what to put in place of the <???>. How do I refer to the instance of the outer class from within the inner static class? What I would like to do is to refer to the implicit this of the OuterClass.


回答1:


You obviously need an object of OuterClass type:

public void someMethod() {
    OuterClass oc = new OuterClass();
    OtherClass.otherMethod(oc);
}

In case that your inner class is not static, then you could do:

//remove static here
private class InnerClass { 
    public void someMethod() {
        OtherClass.otherMethod(OuterClass.this);
    }
}

You should know the different between nested classes - static and non static. Static nested classes are simply classes like every other, just defined within other class (usually because of encapsulation principle). Inner static class instances have no knowledge of outer class instance.

Nested inner classes (non static) mandate that an object of the inner class exist within an instance of the outer class. That's why you can access it via OuterClass.this.




回答2:


The simpliest way is to pass an instance of the outerClass in the constructor or in the method since the innerClass don't know this class.

like this:

public void someMethod(OuterClass outerClass) {
   OtherClass.otherMethod(outerClass.myMethod());
}


来源:https://stackoverflow.com/questions/31835630/java-reference-outer-class-in-nested-static-class

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!