[英]Inheritance method calling - Java
I have a method in a class that sets "Position X" and "Position Y". 我在一个类中设置“位置X”和“位置Y”的方法。
public class Player {
int positionX, postinionY;
public void setPosition (int position_X, int position_Y)
{
positionX = position_X;
postinionY = position_Y;
}
}
I have another class "World" that has an array in it called grid. 我还有另一个类“ World”,其中有一个称为网格的数组。 I have to use the values of position x and y from Player to get location from the grid.
我必须使用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];
}
}
I need help to take Position x,y(Player) and use them instead x,y (World) 我需要帮助以采取x,y(Player)位置,并改用x,y(世界)
You could add another method to World
get the own (the players) location id: 您可以向
World
添加另一个方法来获取自己的(玩家)位置ID:
public int getPlayerLocationID() {
return grid[positionX][positionY];
}
But - honestly - in what kind of universum we have a relation "a world is-a player"? 但是-老实说-在什么样的大学里,我们有一个“世界就是一个玩家”的关系? In all universums that I know (Ok, only one, actually), we usually have "a world has-many players".
在我所知道的所有大学中(实际上只有一个),我们通常都有“一个世界上有很多参与者”。
This method should do what you want. 此方法应做您想要的。
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];
}
}
Note that it will throw an exception in case the arguments provided are not valid. 请注意,如果提供的参数无效,它将引发异常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.