访问在一个类中创建的对象到另一个类

cur*_*gie 5 java class object

我有一个小学课程如下:

public class classB{

  public classC getObject(String getstring){
     return new classC(getstring);
    }
}
Run Code Online (Sandbox Code Playgroud)

classC有一个构造器:

public class classC{

 String string;

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

 public methodC(int i){
   <using the `string` variable here>
 }
}
Run Code Online (Sandbox Code Playgroud)

现在我有一个classA将使用创建的对象classB(当然是一个实例classC).

public classA{
  int a = 0.5;

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

}
Run Code Online (Sandbox Code Playgroud)

这是需要的,因为变量是在用户的某些操作上创建并存储的classB,这将在classC方法中进一步使用.创建一个新对象会将我的变量classB设置为null,这不是预期的.

我怎样才能做到这一点?

Rom*_*n C 1

假设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);
  }
}
Run Code Online (Sandbox Code Playgroud)