我有一个初级类如下:
public class classB{
public classC getObject(String getstring){
return new classC(getstring);
}
}
classC
有一个构造器:
public class classC{
String string;
public classC(String s){
this.string = s;
}
public methodC(int i){
<using the `string` variable here>
}
}
现在我有一个 classA
,它将使用在 classB
中创建的对象(当然,它是 classC
的一个实例) .
public classA{
int a = 0.5;
<Get the object that was created in classB>.methodC(a);
}
这是必需的,因为根据用户的某些操作创建变量并存储在 classB
中,这将在 classC
的方法中进一步使用。创建一个新对象将使我在 classB
中的变量设置为 null,这不是预期的。
我怎样才能做到这一点?
最佳答案
假设 Brand
是轻量级对象而 Run
是重量级对象,那么为轻量级对象创建一个包含容器的字段并将其隐藏是个好主意。
但是 Brand
需要访问它所属的容器,它可以通过映射来完成,但我们只是将 Run
注入(inject) 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);
}
}
关于java - 将一个类中创建的对象访问到另一个类中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10570393/