繁体   English   中英

继承方法调用-Java

[英]Inheritance method calling - Java

我在一个类中设置“位置X”和“位置Y”的方法。

public class Player {

    int positionX, postinionY;

    public void setPosition (int position_X, int position_Y)
    {
         positionX = position_X;
         postinionY = position_Y;
    }

}

我还有另一个类“ World”,其中有一个称为网格的数组。 我必须使用Player的位置x和y的值来从网格中获取位置。

public class World extends Player {
    int [] [] grid = new int [16] [16];

    public int getLocationID (int x, int y)
    {
        return grid [x][y];
    }
}

我需要帮助以采取x,y(Player)位置,并改用x,y(世界)

您可以向World添加另一个方法来获取自己的(玩家)位置ID:

public int getPlayerLocationID() {
    return grid[positionX][positionY];
}

但是-老实说-在什么样的大学里,我们有一个“世界就是一个玩家”的关系? 在我所知道的所有大学中(实际上只有一个),我们通常都有“一个世界上有很多参与者”。

此方法应做您想要的。

public class World extends Player {
    int [] [] grid = new int [16] [16];
    public int getPlayerID (int locationX, int locationY)
    {
        if((locationX>15)||(locationX>16))
            throw new InvalidArgumentException("Player locations should be less than 16!");
        return grid [locationX][locationY];
    }
}

请注意,如果提供的参数无效,它将引发异常。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM