[英]Java - instanceof
首先,我做了一個“游戲渲染器”。
我的問題是,當我需要繪制當前Element時:我需要知道它是Rectangle,Circle還是Image等。
我的課程(矩形,圓形等)是從圖形學擴展的。
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);
}
為了避免使用instanceOf
,讓Graphic
實現抽象的draw
方法。 然后,在Rectangle
, Circle
等類中覆蓋draw
。 那你可以做
for(index = 0;index < graphicObjects.size();index++){
currentElement = graphicObjects.get(index);
currentElement.draw();
}
之所以出錯,是因為您試圖說超型圖形是一個矩形,而不是矩形是一個圖形。
因此,請確保您在超級類型中具有一個函數,並在子類型中對其進行覆蓋,因此您無需進行任何強制轉換。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.