This site requires JavaScript, please enable it in your browser!
Greenfoot back
tjoepapke
tjoepapke wrote ...

2017/7/4

What's the safest casting?

tjoepapke tjoepapke

2017/7/4

#
Hellow, after testing many types of castings, I still wondering about the safest way of some cast, like , private void remove() { Game1 world = (Game1)getWorld(); if(getY()<10) { world.removeObject(this); world.addArrows(-1); } } or private Game3 world; /** * Called when the target is added to the world. */ public void addedToWorld(World world) { this.world = (Game3)world; } are there better ways to cast the world/actor ?
danpost danpost

2017/7/4

#
The casting to Game1 in the remove method is required over casting to World because the addArrows(int) method is not in the World class. I do not see a casting of any Actor objects. You do not necessarily need to restrict objects of the class of the targets to be solely in a Game3 type world. In other words, you can remove the 'world' field and the addedToWorld(World) method and, when needed, test which type world the target is in by checking the world type -- for example:
if (getWorld() instanceof Game3)
danpost danpost

2017/7/4

#
What's the safest casting?
I would not consider safety to be an issue when casting. However, I would cast to the most general type needed (or possible) that works as far as what methods and fields need to be accessed (although, this is more a matter of taste).
tjoepapke tjoepapke

2017/7/5

#
Ty, Danpost for the explanation. I will test those out and reload that project on later stage. (pooh balloon game). I'm still a noob at this moment. And assume that our doc. will prefer the instanceof methods on some parts of the code.
Venbha Venbha

2017/8/5

#
Hello wrote...
if (getWorld() instanceof Game3)
You need to login to post a reply.