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

前端 未结 8 1248
孤独总比滥情好
孤独总比滥情好 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

    0 讨论(0)
  • 2020-11-22 03:15

    Here's the example:

    // Test
    public void foo() {
        C c = new C();
        A s;
        s = ((A.B)c).get();
        System.out.println(s.getR());
    }
    
    // classes
    class C {}
    
    class A {
       public class B extends C{
         A get() {return A.this;}
       }
       public String getR() {
         return "This is string";
       }
    }
    
    0 讨论(0)
提交回复
热议问题