【问题标题】:Java - instanceofJava - 实例化
【发布时间】:2015-05-02 13:25:39
【问题描述】:

首先,我制作了一个“游戏渲染器”。

我的问题是,当我需要绘制当前元素时:我需要知道它是矩形、圆形还是图像等等。

我的类(矩形、圆形...)是从 Graphic 扩展而来的。

public class Rectangle extends Graphic {...}

如果我想画它们,我会在列表中查看ArrayList<Graphic>

for(index = 0;index < graphicObjects.size();index++){
    currentElement = graphicObjects.get(index);

    if(currentElement instanceof Rectangle) { // Here is an error.
    Rectangle r = (Rectangle) currentElement;
    // here the drawing.
    }
}

感谢您的帮助(Goggle 没有帮助):)

编辑:

错误是:“不兼容的条件操作数类型图形和矩形”

以及为什么我需要知道类型: 我的代码:

public static Image getImage(Graphics g,int width, int height) {
    int imgWidth = width;
    int imgHeight = height;
    BufferedImage bfImage = new BufferedImage(imgWidth, imgHeight, BufferedImage.TYPE_INT_ARGB);
    Graphics graphics = bfImage.getGraphics();

    for (int index = 0; index < grObjList.size(); index++) {
        Graphic gr = grObjList.get(index);
        if(gr instanceof Rectangle){
            graphics.setColor(gr.color);
            graphics.fillRect(gr.x, gr.y, gr.width, gr.height);
        }
    }
    return bufferedImagetoImage(bfImage);
}

【问题讨论】:

  • 错误是什么?
  • 为什么需要知道类型?虚拟方法和继承的重点是您不需要知道类型。只需创建一个绘图函数并在子类中覆盖它...
  • 一般来说,你应该遵循上面 nneonneo 建议的做法和 pathfinderelite 的回答。但是,如果您使用 eclipse,为了解开这个谜,请在此处查看投票最多的答案:stackoverflow.com/questions/2551337/…
  • 检查您的导入。很可能您导入了错误的 Rectangle。

标签: java extends instanceof


【解决方案1】:

为避免使用instanceOf,让Graphic 实现抽象draw 方法。然后,在 RectangleCircle 等类中覆盖 draw。然后就可以了

for(index = 0;index < graphicObjects.size();index++){
    currentElement = graphicObjects.get(index);
    currentElement.draw();
}

【讨论】:

  • 这个版本效果最好,但没有解决我需要的问题/问题。因为我不理解“扩展”:矩形从图形扩展,所以矩形是图形。如果我把它放在图形列表中,我应该检查它是否是矩形、圆等......也许我以后需要它。
【解决方案2】:

您遇到错误是因为您试图说超类型 Graphic 是一个 Rectangle 而不是 Rectangle 是一个 Graphic。

所以请确保您在超类型中有一个函数并在子类型中覆盖它,这样您就不需要进行任何转换。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-06-10
    • 1970-01-01
    • 2020-07-29
    • 2013-03-29
    • 2021-05-14
    • 1970-01-01
    • 1970-01-01
    • 2017-10-22
    相关资源
    最近更新 更多