【问题标题】:Can't create a Object无法创建对象
【发布时间】:2015-03-19 00:38:27
【问题描述】:

我有一个包含多个类的应用:

MenuActivity、MenuThread、MenuView、MenuBot、MenuBall。

在“MenuView”类中,我声明了我需要的所有 ib 对象:

this.ball = new MenuBall(this, bot1);    
this.bot1 = new MenuBot1(this, ball);    
this.thread = new MenuThread(this,bot1,ball);

如您所见,我还没有创建对象 bot1,但我已经将它用作对象球中的参数,这给了我错误。

感谢您尝试帮助我!

【问题讨论】:

  • 循环依赖!不好的方法!
  • 你想在MenuBall 的构造函数中对bot1 做什么?您不能在创建对象之前使用它们 - Java 无法预测对象将来会是什么。
  • @SanPonko Bot1 应该改变自己的方向。那么 Ball 不需要知道 Bot1。但最好让碰撞检测远离实体类。
  • @vakio 但 Bot1 不应该改变自己球应该改变的方向。
  • @Tanis.7x Bot1 需要获取 Ball 的参数以检测它们是否发生碰撞。如果是这种情况,球正在改变方向

标签: java android object parameters constructor


【解决方案1】:

您必须更改(或添加其他)MenuBall 和 MenuBot1 的构造函数。 因此,例如:

public class MenuBall {
    private MenuBot1 menuBot1;
    (...)

    // this constructor doesn't need a MenuBot1 object.
    public MenuBall(MenuView menuView) {
        (...)
    }

    // setter for the menuBot1
    public void setMenuBot1(MenuBot1 menuBot1) {
        this.menuBot1 = menuBot1;
    }

    (...)
}

public class MenuBot1 {
    private MenuBall menuBall;
    (...)

    // this constructor doesn't need a MenuBall object.
    public MenuBot1(MenuView menuView) {
        (...)
    }

    // setter for the menuBall
    public void setMenuBall(MenuBall menuBall) {
        this.menuBall = menuBall;
    }

    (...)
}

然后在 MenuView 类中:

ball = new MenuBall(this);
bot1 = new MenuBot1(this);
ball.setMenuBot1(bot1);
bot1.setMenuBall(ball);
thread = new MenuThread(this, bot1, ball);
(...)

【讨论】:

    猜你喜欢
    • 2013-10-22
    • 2017-10-01
    • 2013-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多