Java: reference outer class in nested static class

This question already has an answer here:

  • Java inner class and static nested class 23 answers

  • 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 .


    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());
    }
    
    链接地址: http://www.djcxy.com/p/92014.html

    上一篇: 为什么LinkedList中的类节点被定义为静态而不是普通类

    下一篇: Java:在嵌套静态类中引用外部类