Terence Chow
Terence Chow

Reputation: 11153

how to reference an instance created in another class

I have a function in Class A which I would like to change the value of a field in Class B.

Class C has my main() and creates a new instance of class B and Class A. Class A is from an API and one of their functions is a listener function. I would like for that listener function to be able to change the field of Class B, but when I write the code for the listener function, it doesn't recognize Class B's instance.

How do I reference that instance?

Example code:

public class A {
     public void listenermethod(){
            //can't reference Binstance <-------
     }
}

public class B {
     B.field = 1;
}

public class C {
     A Ainstance = new A();
     B Binstance = new B(); 
}

Upvotes: 2

Views: 917

Answers (3)

Crowbar
Crowbar

Reputation: 679

An instance by definition belongs to an object. Therefore, your class A must either have an object of class B as a member:

Class A{

     private B instance_of_b;

}

now you can access B members like this:

instance_of_b.member

or the field belonging to class B could be static and then A could access it through the class.

B.member

Also make sure you know the meaning of accessor keywords (private,protected,[friendly],public).

Upvotes: 0

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285405

You should give A class a private B field, and then you can call the public methods from B on this field as needed. If you need to create both A and B instances in a separate class (C) you should give your A class a public void setB(B b) setter method.

A.java

class A {
  private B b;

  public void setB(B b) {
    this.b = b;
  }

  public void listenerMethod() {
    if (b != null) {
      b.someBMethod();
    }
  }
}

C.java

public class C {

  public static void main(String[] args) {
    A a = new A();
    B b = new B();
    a.setB(b);

    a.listenerMethod();

  }
}

Upvotes: 2

Kyle
Kyle

Reputation: 4298

You have to be able to modify both class C and class A. Rewrite the class A method to

public void listenermethod(Binstance theB){
            theB.something = "some_value";
     }

Now when you call class A, pass in the Binstance. If you can't modify class A, then your task can't be done.

Upvotes: 0

Related Questions