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

Report as inappropriate.

davmac presents ...



This scenario is part of a tutorial about accessing objects from another. See the tutorial here:


This is a simple game. Press space bar to fire a shot at the asteroids which go past overhead. There is a delay between each shot so you must aim carefully.

The counter at the bottom left is meant to be a score. It isn't functional. Making it work is what the tutorial is all about!

47253 views / 3247 in the last 7 days

4 votes | 0 in the last 7 days

Tags: game with-source howto

open in greenfoot
Your browser does not support the canvas tag.




Could you explain to me what this line of code does: Space spaceWorld = (Space) getWorld(); What do the parentheses mean when you put them around "(Space)"?


'getWorld' return a World object (not particularly a 'Space' object; though it could be one). That is what '(Space)' does. It makes it a 'Space' object. This is called 'typecasting' and it informs the system to look in the 'Space' class for any methods or fields referenced with the World object. Any methods or fields that are declared in the 'Space' class would not be found otherwise.


davecoolkid: as danpost says 'getWorld()' returns a 'World', but in the line of code you specify the variable is of type 'Space'. The compiler doesn't let you assign just a World to a Space variable (even though the World *might* be a Space). In this case we know that the world definitely *is* a space, so we use this type cast to tell the compiler that it's ok. A simple experiment you can do is to remove the type cast (the "(Space)" part) and try to compile. What happens?


Thanks danpost and davmac for the clarification helped me out a lot.


Geez, i made a game myself much like this (as in space and stuff) and what suprised me after checking this page is that the space icon that is used here is IDENTICAL. It doesn't help either that the theme is much the same too. I'll just hope my teacher will believe that it is still original XD. Well, atleast i have a fancy movement engine.


Might I humbly suggest an alteration to the code in the Space class: addObject(new Counter(), 40, 340); this needs changing to: addObject(theCounter, 40, 340);


Otherwise, great tutorial...Thanks


private Counter theCounter; /** * Constructor for objects of class Space. */ public Space() { // Create a new world with 600x400 cells with a cell size of 1x1 pixels. super(600, 400, 1); theCounter = new Counter(); addObject(new Rocket(), 300, 340); addObject(theCounter, 40, 340); }


See the description of the scenario: “The counter at the bottom left is meant to be a score. It isn't functional. Making it work is what the tutorial is all about!”

See all comments

Want to leave a comment? You must first log in.

Who likes this?

data17 tehbestcoder Antonio wwwayne