Getting hold of the outer class object from the inner class object

前端 未结 8 1467
孤独总比滥情好
孤独总比滥情好 2020-11-22 02:26

I have the following code. I want to get hold of the outer class object using which I created the inner class object inner. How can I do it?

pub         


        
8条回答
  •  梦谈多话
    2020-11-22 03:13

    The more general answer to this question involves shadowed variables and how they are accessed.

    In the following example (from Oracle), the variable x in main() is shadowing Test.x:

    class Test {
        static int x = 1;
        public static void main(String[] args) {
            InnerClass innerClassInstance = new InnerClass()
            {
                public void printX()
                {
                    System.out.print("x=" + x);
                    System.out.println(", Test.this.x=" + Test.this.x);
                }
            }
            innerClassInstance.printX();
        }
    
        public abstract static class InnerClass
        {
            int x = 0;
    
            public InnerClass() { }
    
            public abstract void printX();
        }
    }
    

    Running this program will print:

    x=0, Test.this.x=1
    

    More at: http://docs.oracle.com/javase/specs/jls/se7/html/jls-6.html#jls-6.6

提交回复
热议问题