像这样做 :
main
或者你正在初始化的地方将两个对象都传递给它 Container
public static void main(String args[]){
Box box1 = new Box();
Toy toy1 = new Toy();
Container c = new Container(box1, toy1);
box1.open();
toy1.play();
//or pass both object where ever you want without recreating them
}
class Container {
Box box1 = new Box();
Toy toy1 = new Toy();
public Container(Box box1, Toy toy1){
this.box1 = box1;
this.toy1 = toy1;
}
}
更新:现在根据您的需要以下解决方案,但我也不喜欢这样做:
class Container
{
public Box box1 = new Box(); // should not be public but as your needs
public Toy toy1 = new Toy(); // should not be public but as your needs
}
container.box1.open();
container.toy1.play();