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

2016/10/24

Calling World public method from Actor subclass

EGrant EGrant

2016/10/24

#
I have created a public method in a World subclass, and I am unable to call the method from within an Actor subclass method. The error I get is "cannot find symbol". I have chosen to replicate this problem in a book_scenario: Newtons-Lab-1 in the constructor for the SmoothMover subclass as follows:
1
2
3
4
5
6
7
8
/**
 * Default constructor.
 */
public SmoothMover()
{
    this(new Vector());
    getWorld().sunAndPlanet();
}
I found this inconsistent since I have always been able to call World methods (such as addObject) from within an actor subclass so long as I reference the World object. The problem I am having in my scenario is the same as this one. I am able to call the method directly when I right-click on the World from the drop down box (just as I am able to within the Newtons-Lab-1 scenario), but not able to call it from within an Actor subclass method. Appreciate the help, Elizabeth
danpost danpost

2016/10/24

#
The reason methods like 'addObject' works when using 'getWorld' is because 'getWorld' returns a World object (or null). As a World type, methods of the World class are accessible. However, for methods of a subclass of World, you need to inform the compiler where to look for that method. This is done by typecasting. If the name of the subclass were MyWorld, then:
1
((MyWorld)getWorld()).sunAndPlanet();
or
1
2
MyWorld myWorld = (MyWorld) getWorld();
myWorld.sunAndPlanet();
EGrant EGrant

2016/10/24

#
Thanks Dan. I haven't taken advantage of World subclasses much yet. The explanation is totally reasonable since, after all, the method belongs to the subclass not World, unlike the addObject method.
You need to login to post a reply.