Results 1 to 2 of 2
  1. #1
    blug is offline Member
    Join Date
    Oct 2010
    Rep Power

    Default 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.

    PHP Code:
    ClassC cOBJ = new ClassC(this);
    I would obviously have the constructor in ClassC have something like this...

    PHP Code:
    ClassC(ClassB cOBJ){
    this.cOBJ =  cOBJ;
    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.

    Thankyou! Sorry if what I said was a bit confusing xD

  2. #2
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Rep Power

    Default 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.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

Similar Threads

  1. accessing class methods or fields or variables
    By noobplus in forum New To Java
    Replies: 8
    Last Post: 03-12-2012, 01:34 PM
  2. Accessing methods in a different class
    By syle_q in forum New To Java
    Replies: 6
    Last Post: 03-30-2011, 07:39 PM
  3. Problems accessing methods in an object.
    By Kevinius in forum New To Java
    Replies: 2
    Last Post: 03-05-2011, 10:52 AM
  4. Replies: 5
    Last Post: 10-11-2010, 01:16 AM
  5. Accessing GUI object methods
    By km0r3 in forum AWT / Swing
    Replies: 5
    Last Post: 10-06-2010, 01:39 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts