0

我有一个带有对象的类现在我想从 Container 类外部的 Box 和 Toy 对象中调用一个函数

class Container
{
   Box box1 = new Box();
   Toy toy1 = new Toy();
   public void open()
   {
      box1.open();
   }
   public void play()
   {
      toy1.play();
   }
}

如何避免重新创建方法并仅与 Container 类共享方法。我不能使用继承,因为我有 2 个或更多对象。

4

2 回答 2

1

您可以按如下方式进行。

public interface ToyInterface {
    public void play();
}

public class Toy implements ToyInterface {
    @Override
    public void play() {
        System.out.println("Play toy");
    }
}

public interface BoxInterface {
    public void open();
}

public class Box implements BoxInterface {
    @Override
    public void open() {
        System.out.println("open box");
    }
}

public class Container implements ToyInterface, BoxInterface {
    private BoxInterface box;
    private ToyInterface toy;

    public Container() {
        box = new Box();
        toy = new Toy();
    }

    public BoxInterface getBox() {
        return box;
    }

    public ToyInterface getToy() {
        return toy;
    }

    @Override
    public void play() {
        System.out.println("play container");
        this.toy.play();
    }

    @Override
    public void open() {
        System.out.println("open container");
        this.box.open();
    }
}

然后你就可以在 Container 之外访问 Box 和 Toy 类的方法。

Container container = new Container();
container.open();
container.getBox().open();

container.play();
container.getToy().play();
于 2012-08-02T11:33:51.950 回答
0

像这样做 :

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();
于 2012-08-02T11:48:18.610 回答