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

前端 未结 8 1372
孤独总比滥情好
孤独总比滥情好 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: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";
       }
    }
    

提交回复
热议问题