Search code examples
javacontain

Accessing fields and methods of object containing 'this' object


Sample code:

public class A {
    B b = new B();
    int a = 17;
}

public class B {
    int getA() {
        // how to get 'a' field from object containing 'this' object 
    }
}

My question is as in comment in sample code. In general: how to access fields and methods from object containing 'this' object. In my example class B will be instantiated only as a field in class A.


Solution

  • If your starting point is code in B, then you can't do that. There's no way to reach out and find everywhere that B is used in all classes in the VM.

    Moreover, though, if you find yourself wanting to do that, it indicates that you need to revisit your class structure. For instance, you might have B accept an A argument in the B constructor:

    public B(A owner) {
        // ...do something with owner object
    }
    

    That introduces fairly tight coupling between A and B, though, which can be an issue. You might instead abstract away the aspects of A that B needs to know about into an interface, have A implement that interface, and have B accept an argument typed using that interface.

    Or avoid needing to have B know anything about A, which would usually be best.