Question

Code:

public class A{
  B b = new B();

  public class B{
    public void fun(){ send(A); }
  }

I want to do something with all A object in B. I can create method in A class:

private A getThis(){return this;}

But is it other solution (some keyword)?

Was it helpful?

Solution

Try this code inside your inner class.

A.this

It should give you a reference to the enclosing instance from the outer class.

Here is a small example.

public class A {
    private B b = new B();

    public class B {
        public void fun() {

        }
        public A getEnclosing(){
            return A.this;
        }
    }

    public static void main(String[] args){
        A a = new A();
        System.out.println(a == a.b.getEnclosing());
    }
}

OTHER TIPS

Try

B b = new B(this);

Then B contructor

public B(A a) {
    this.a = a;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top