Access object created in one class in another

I have a main class as shown below:

public class classB{

  public classC getObject(String getstring){
     return new classC(getstring);
    }
}

classC has a constructor:

public class classC{

 String string;

 public classC(String s){
  this.string = s;
 }

 public methodC(int i){
   <using the `string` variable here>
 }
}

Now I have classAone that will use the object created in classB(which, of course, is an instance classC).

public classA{
  int a = 0.5;

  <Get the object that was created in classB>.methodC(a);

}

This is necessary because the variable is created during some user actions and stored in classB, and this will be used later in the methods classC. Creating a new object will make my variable classBequal to zero, which is not intended.

How can i achieve this?

+5
source share
2 answers

, Brand - , Run - , - .

Brand , , , Run Brand, Runable JSR330. Run .

class MainClass {
  public static void main(String[] args) {
    Run r = new Run();
  }
}

class Run {
  private Container con1 = new Container();

  public Run() {
    Brand cola = new Brand("Coca Cola");
    Brand pepsi = new Brand("Pepsi");

    // Creates the container object "con1" and adds brands to container.
    add(cola);
    add(pepsi);
  }
  public void add(Brand b){
    con1.addToList(b);
    b.setRun(this);
  }

  public Container getContainer() {
    return con1;
  }
}

class Brand {
  // In this class I have a method which needs to accsess the con1 object
// containing all the brands and I need to access the method
  private String name;
  private Run run;

  public Brand(String name){
    this.name = name;

  }
  public void brandMethod() {
    if(getRun().getContainer().methodExample()) {        // Error here. Can't find "con1".**
      System.out.println("Method example returned true.");
    }
  }


  public Run getRun() {
    return run;
  }

  public void setRun(Run run) {
    this.run = run;
  }
}

class Container {
  // This class is a container-list containing all brands brands
  private ArrayList<Object> list = new ArrayList<Object>();

  public boolean methodExample(){
    return false;
  }

  public void addToList(Object o) {
    list.add(o);
  }
}
+1

, B,

public class classB {

  public static objectCReference;

  public classC getObject(String getstring){
     objectCReference =  new classC(getstring);
     return objectCReference;
  }
}

A

public classA {
  int a = 0.5;

  if (classB.objectCReference != null) { // Make sure to null check 
    classB.objectCReference.methodC(a); 
  }

}

.

0

All Articles