2012-08-02 113 views
0

我有对象 类现在我想从我怎样才能避免重新创建方法,只是容器类共享一个场法

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

外面打电话从盒和玩具对象的功能与Container类共享方法。 我不能使用继承,因为我有2个或更多的对象。

+0

你的方式是罚款,因为它可以。 – 2012-08-02 11:05:58

+0

听起来就像组成一样,就像你现在正在做的那样。 – Ushox 2012-08-02 11:10:18

+0

好的,因为没有更好的解决方案,我会用我原来的方法。 – 2012-08-02 13:57:55

回答

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之外的方法。

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

container.play(); 
container.getToy().play(); 
+0

好吧,对不起,我应该说一个“简单”的解决方案:) – 2012-08-02 11:39:15

+0

它看起来很复杂,但简而言之,它意味着当你需要使用多重继承时使用接口。 – 2012-08-02 11:48:15

+1

这实际上并不是我想要拯救我的一些工作,但感谢无论如何,这是做到这一点的一种方式。 – 2012-08-02 14:00:48

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; 
    } 
} 

UPDATE:现在按照你的需要以下解决方案,但我也不喜欢这样做:

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(); 
+0

这完全忽略了问题的关键。 OP希望你**删除“open”和“play”**的声明,并让解决方案继续工作。 – 2012-08-02 12:01:48

+0

@MarkoTopolnik现在可以了.. ?? – 2012-08-02 12:26:59

+0

我会把这当作玩笑:) – 2012-08-02 12:31:18