【发布时间】:2011-12-10 14:23:52
【问题描述】:
我有两个抽象类,分别称为 Robot 和 GeometricElement。
它们中的每一个都有子类。
我需要构建一个包含Robot 或GeometricElement 的NxM 矩阵,所以
我已经写了另一个类并称之为Item,然后是Robot 和GeometricElement
从那个类继承。
代码如下:
public class Item {
private Dot currentLocation;
private boolean taken;
public Item(Dot location) {
int x = location.getXcomponent();
int y = location.getYcomponent();
currentLocation = new Dot(x,y);
taken = false;
}
// more code
}
public abstract class GeometricElement extends Item {
private float area;
public GeometricElement(Dot location) {
super(location);
}
}
public abstract class Robot extends Item {
private float basketArea;
/* Constructor */
public Robot(Dot location, float basketNewArea) {
super(location);
basketArea = basketNewArea;
}
// some more code
}
负责存储Items 的类称为 Ground :
public class Ground {
private Item[][] board;
private Queue elementQueue;
/* Constructor */
public Ground(int row,int col) {
board = new Item[row][col];
this.elementQueue = new Queue();
}
// more code
public void addElementsToRobot() {
while (this.elementQueue.doesQueueHasItems()) {
GeometricElement element = elementQueue.popElementFromQuque();
int x = element.getXlocation();
int y = element.getYlocation();
if (this.board[x][y].isTaken()) {
if (board[x][y] instanceof Robot) {
// add geometric element to the basket
}
}
}
}
}
如上所述,我需要在板上存储Robot 或GeometricElement。当我尝试从矩阵(“地面”中的“板”矩阵)读取时,问题就开始了:我似乎无法找到一种方法来判断单元格中是否有机器人或几何元素,而不使用 @ 987654333@.
【问题讨论】:
-
为什么您需要知道您拥有的是
Robot还是GeometricElement?扩展基类的全部意义在于避免显式检查。 -
为什么不想使用instanceof?在你的情况下,这似乎是最合乎逻辑的。
-
因为机器人能够将 GeometricElement 添加到篮子中(抱歉之前没有提及)。
-
@ron:如果您只想访问
Robot实例,您可能不应该维护一个通用Items 的容器。使用基类的全部意义在于您可以愉快地说“我不在乎”。 -
Oli,我这里别无选择。这是作业的规则:使用 NxM 矩阵,并将 Robot/GeometricElement 存储在其中。我认为您确实是对的,但我没有在这里选择。
标签: java inheritance abstract-class