I have an objectA from ClassA which has a List of objects from ClassB.
Can I access objectA from objectB? I mean, I’m asking if there are something like objectB.getListOwner() which returns objectA.
I know I can have a ClassA atribute on ClassB and set it with objectA when I create objectB but I’m wondering if there are something more direct.
Not directly or automatically.
What you can do is have a method in ClassA such as
addToList(ClassB objectB)and what this does is the following:
And you use that method to add
ClassBobjects to the list ofClassA.Obviously
ClassBneeds to have a methodsetClassAOwner(ClassA owner)and the respective member variableClassAowner, and most probably a matching getter methodgetClassAOwner()Small comment with regards to this approach. This introduces a direct cyclic dependency, which is, more often than not, undesirable from a Design principle point of view for various reasons outside scope of this question. But it achieves what you want.