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

2014/10/27

Actors communicating with a World subclass

forteddyt forteddyt

2014/10/27

#
Hello, I wanted to know if there is a way to call a World subclass method by an actor. As in, my actor Bob can call getWorld().addObject(new Wife(pretty), getX(), getY()); because that is a direct method that the World has (the method being addObject()). But if I were to make a new subclass of World, called Home, and I were to construct a new static method in Home called decorateHome(Object furniture, int x, int y), how could Bob decorate his and his new Wife's home with a pottedPlant at location (42, 42)?
danpost danpost

2014/10/27

#
First, you would not want the 'decorateHome' method to be static. The class could not possibly know which Home world object created from it that you would want decorated. You would want to have a world object decorate itself with the furniture by calling the method. As a non-static method, a Home world object would be the object the method would execute for. You can use the 'getWorld' method of the Actor class to acquire a reference to the world that actor is in, and then typecast it as a Home world object so you can run the method on that world:
Home home = (Home)getWorld(); 
home.decorateHome(new PottedPlant(), 42, 42);
// or simply
((Home)getWorld()).decorateHome(new PottedPlant(), 42, 42);
The 'getWorld' method returns an object typed as a World object. This object must be made known to the compiler that it is indeed a Home world object for it to look in the Home class for the method you wrote there.
forteddyt forteddyt

2014/10/27

#
Got it, works now, thanks for the help :)
leuveg leuveg

2015/2/17

#
<edit> wrong thread
You need to login to post a reply.