Accessing methods from object in another class.
Hello, basically I am currently doing a bit of work with Swing but I have come off with a bit of problem with my class hierarchy (Nothing to really do with Swing, just a general java problem).
So basically I have Class A, Class B, and Class C.
From Class A, I created an Object of Class B. Within Class B, I created an object of class C. I am now wanting to access methods within the object of Class B from my Class C object.
What would be the best way to do this in your opinion? I was thinking a simple solution would be to have a parameter when I create the class C which would be kind of like.
I would obviously have the constructor in ClassC have something like this...
ClassC cOBJ = new ClassC(this);
If you don't really understand the dilemma I am in... It's easy enough for me to just create a brand new Class B object within Class C, however, I want to have full access to all of my previous variables within Class B, so creating a brand new Object will obviously not work out. I need to access the exact Class B Object that was created within class A so I can have full access to it's methods.
this.cOBJ = cOBJ;
Thankyou! Sorry if what I said was a bit confusing xD
Re: Accessing methods from object in another class.
That is one way of doing it yes.
It all depends on exactly why you need to access B from within C.
If it is so that B can react when something happens in C then I would create an interface with relevant methods, then have B implement that.
You would still pass B in, but C will then not actually know about B, it will simply know about the interface.
This is a Listener pattern, or Observer pattern.