Your original code:
public void tick() {
for(int i=0; i < handler.object.size() ;i++) {
GameObject tempObject = handler.object.get(i);
if (tempObject.getId() == ID.FlashCardCover){
//run a method in FlashCardCover class on this individual object
}
}
}
If I interpret this correctly, you have some GameObject
s and one of the kinds of GameObject is a FlashCardCover
. You determine this by checking the "Id" (which I would call "TypeId" or just "Type")
So as you loop through your GameObjects, you want to call some method when that particular GameObject is in fact a FlashCardCover. You would do that by invoking the method on that object, say like tempObject.uncoverCard()
— but of course you can't do that because a GameObject doesn't have an uncoverCard method.
This is where you use a cast
public void tick()
{
for (int i=0; i<handler.object.size(); i++)
{
GameObject tempObject = handler.object.get(i);
if (tempObject.getId() == ID.FlashCardCover) {
FlashCardCover c = (FlashCardCover) tempObject;
c.uncoverCard();
}
}
}
You have cast the tempObject
to be a FlashCardCover
and that is an object on which you can call your "uncoverCard" method.
The cast doesn't have to be done in two lines (I did that for clarity) -- you can cast and call at the same time, such as ((FlashCardCover) tempObject).uncoverCard()
Note that this all assumes that FlashCardCover is a subclass of GameObject, e.g.
public class FlashCardCover extends GameObject { ... }
If it doesn't you'll get a ClassCastException
Now with all that explained ... you don't need your own type codes to do this sort of casting, you can use instanceof
instead.
if (tempObject instanceof FlashCardCover) {
// do your thing
}