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

2023/2/6

Casting

SANELE SANELE

2023/2/6

#
can someone please explain to me Casting with examples.
danpost danpost

2023/2/6

#
SANELE wrote...
can someone please explain to me Casting with examples.
Let's say you had in your MyWorld class a method that you wanted to call from an Actor subclass. Maybe your character dies and you want the world to show a game over screen, so you want to call the gameOver method:
/**  In Actor subclass  */
// case 1:  assigning the world to a field that holds a World object
World world = getWorld();
// "world.gameOver();" will not work as "world" is not cast as a MyWorld object, but
((MyWorld)world).gameOver(); // will work

// case 2: assigning the world to a field that holds a MyWorld object
MyWorld world = (MyWorld) getWorld();
world.gameOver();

// case 3: casting and calling the method in one statement
((MyWorld) getWorld()).gameOver();
Casting to any subclass of MyWorld will still access the method; however, casting only need be to the subclass of Object that contains the method (or field) that needs accessed.
You need to login to post a reply.