【问题标题】:Can I "extend" a method, or call a method inside of another one?我可以“扩展”一个方法,或者在另一个方法中调用一个方法吗?
【发布时间】:2021-05-26 23:17:37
【问题描述】:

*我正在开发一款游戏,该游戏在棋盘上只有棋子。棋子可以移动,也可以拿走对手的棋子。移动它向前移动一格,将它向前移动一格,然后向一侧移动。 由于移动动作也是每个采取动作的一部分,我想知道我是否可以以某种方式将这两者结合起来。我试图将 move 方法集成到我的 take 方法中,但它不起作用,据说是因为该方法不知道它与哪个片段相关联。 这两种方法都会改变我的作品的属性(x 坐标和 y 坐标)以标记它在棋盘上的位置。 我可以用其他方式吗?

    /*
     * move action
     * differentiates between Black and White pieces, so both use the same method to move
     */
    public void move() {

        switch(color) {
        case "White":
            this.yCo = this.yCo+1;
            break;
        case "Black":
            this.yCo = this.yCo-1; 
            break;
        }

    }

    /*
     * take action
     * moves one tile forward and one tile to either left or right and removes an opponents piece on that tile
     */
    public void takeRight() {
        
        this.move();
        
        this.xCo = this.xCo+1;

    }
```*

【问题讨论】:

  • 是的,可以从另一个方法中调用一个方法。 确切地对您来说是什么意思,“据说是因为该方法不知道它与哪个部分相关联”?当您尝试发布的代码时究竟发生了什么?
  • @JonSkeet 实际上我修复了那个代码,因为我的 switch 语句错过了一个中断。但是当我像在我的示例中那样编译它时, take() 中的 move() 只是被跳过了。
  • 我认为这不太可能,我认为您误诊问题的可能性更大。不过,如果没有更多信息,我们真的无法判断——最好是minimal reproducible example
  • @JonSkeet 你是对的!

标签: java inheritance methods


【解决方案1】:
public void move(int xShift) {
    switch(color) {
        case "White":
            this.yCo = this.yCo+1;
            break;
        case "Black":
            this.yCo = this.yCo-1; 
            break;
    }
    this.xCo += xShift;
}

this.xCo += xShiftthis.xCo = this.xCo + xShift 的缩写。你也可以去掉这个多余的

【讨论】:

    猜你喜欢
    • 2015-01-04
    • 1970-01-01
    • 2014-02-23
    • 2017-02-15
    • 2010-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-15
    相关资源
    最近更新 更多